객체에 메모리가 어떻게 만들어지나2(feat. 오버로딩)

Muhly·2023년 3월 18일
0

oop

목록 보기
4/8

✏️생성자 메서드

  • 객체를 생성할 떄 사용되는 메서드
  • 객체 생성 후 객체의 초기화를 하는 역할 수행
  • 특징
    • 클래스이름과 동알한 메서드
    • 메서드의 return type 이 없다(void)아님
    • public접근 권한을 가진다.(단, private 생성자도 있음)
    • 생성자가 없을 떄는 기본 생성자가 만들어진다)

✏️코드를 봐보자!

package oop;

public class TPC12 {
    public static void main(String[] args) {
        //생성자 -> 생성 + 초기화 -> 중복정의
        StarbucksVO b1 = new StarbucksVO();
        System.out.println(b1.cafe + "\t");
        System.out.println(b1.price + "\t");
        System.out.println(b1.company + "\t");
        System.out.println(b1.number + "\t");

        StarbucksVO b2 = new StarbucksVO();
        System.out.println(b2.cafe + "\t");
        System.out.println(b2.price + "\t");
        System.out.println(b2.company + "\t");
        System.out.println(b2.number + "\t");

        StarbucksVO b3 = new StarbucksVO("청주점",30000,"ssg",4);
        System.out.println(b3.cafe + "\t");
        System.out.println(b3.price + "\t");
        System.out.println(b3.company + "\t");
        System.out.println(b3.number + "\t");

    }
}
package oop;

public classStarbucksVO {
publicString cafe;
public intprice;
publicString company;
public intnumber;
//디폴트 생성자 메서드(생략)
publicStarbucksVO(){
//초기화 작업_개발자가 원하는 값으로 마음대로 할 수 있어야 한다
//자기 자신을 가리킴
this.cafe = "서울";
this.price = 70000;
this.company="ssg";
this.number=15;
    }
//생성자 메서드의 중복정의(오버로딩)_하나의 클래스 안에 이름이 같은게 여러개 정의
publicStarbucksVO(String cafe,intprice, String company,intnumber){
this.cafe = cafe;
this.price = price;
this.company = company;
this.number = number;

}
}

서울	
70000	
ssg	
15	
서울	
70000	
ssg	
15	
청주점	
30000	
ssg	
4

✏️오버로딩을 사용하는 이유?

❗️오버로딩을 사용하는 이유는 무엇일까요?

  같은 기능을 하는 메서드를 하나의 이름으로 재활용 하여 절약할 수 있기 때문입니다!!!

오버로딩은 메서드 오버로딩과 생성자 오버로딩이 있으며 실제 적용되는 것은 같습니다.

같은 이름의 함수(메서드)를 여러 개 정의하고, 매개변수의 유형과 개수를 다르게 하여 다양한 유형의 호출에 응답할 수 있도록 하는 방식입니다.

'메서드의 이름은 같지만 매개변수의 개수나 타입이 반드시 달라야함”

profile
https://muhlysstudynote.tistory.com/-> 블로그 이전하였습니다

0개의 댓글