[JAVA] this / 메소드 체이닝 / 생성자 / 인스턴스 멤버 / 클래스 멤버

Gabriela·2023년 7월 20일
0

JAVA

목록 보기
9/24

‣ this

  • 필드나 메소드를 호출하는 객체의 참조값이다.
  • 클래스 내부에서만 사용할 수 있는 키워드이다.

▾ 활용 예제

// 필드
  private double value;
 
//Setter
  public void setValue(double value) {    
  // 필드와 파라미터의 이름이 동일한 경우 그 둘을 구분 할 때 this를 활용한다. (필드앞에 this.를 붙임)
    this.value = value;
  } 

▾ this를 이용해서 메소드 체이닝 하기


계산기 클래스

public class ChainCalculator {
 
  /**
   * 필드 value는 사칙연산의 결과를 저장하고 있다.
   */
  private double value;
 
  public void printThis() {
    System.out.println("현재 객체(printThis 메소드를 호출한 객체)의 참조값: " + this);
  }
 
 
  //Setter
  public void setValue(double value) {    
  // 필드와 파라미터의 이름이 동일한 경우 그 둘을 구분 할 때 this를 활용한다. (필드앞에 this.를 붙임)
    this.value = value;
  }
 
  //Getter
  private double getValue() {
    return value;
  }
 
  public ChainCalculator on() {
    System.out.print(value);
    return this;
  }
 
 
  public ChainCalculator addition(double a) {
    value += a;
    System.out.print("+" + a);
    return this;
  }
 
  public ChainCalculator substraction(double a) {
    value -= a;
    System.out.print("-" + a) ;
    return this;
  }
 
  public ChainCalculator multiplication(double a) {
    value *= a;
    System.out.print("*" + a);
    return this;
  }
 
  public ChainCalculator division(double a) {
    value /= a;
    System.err.print("/" + a);
    return this;
  }
 
  public void done() {
    System.out.println("=" + value);
  }
}

메인 클래스

  public static void main(String[] args) {
   
    // ChainCalculator 객체 선언 & 생성
    ChainCalculator myCalc = new ChainCalculator();
   
    // 객체 자체는 참조값이다.
    System.out.println(myCalc);
   
    // myCalc 객체가 호출한 printThis 메소드이기 때문에,
    // 여기서 확인된 this 값은 myCalc 객체의 참조값과 같다.
    myCalc.printThis();
  
    // myCalc 메소드 체이닝
   	myCalc.on().addition(3).substraction(2).multiplication(5).division(2).done(); 
    // 0.0+3.0-2.0*5.0/2.0=2.5 // 연산 우선순위 없음
   
    // this == myCalc
  }

‣ 생성자(constructor)

  • 객체를 생성할 때 사용하는 메소드이다.

  • new 키워드 이후에 호출된다.

특징

 1) 생성자도 메소드이다.
 2) 생성자의 이름은 클래스의 이름과 같다. 바꿀 수 없다.
 3) 반환(return)이 존재하지 않는다. 반환(return)이 없다는 의미의 void가 아니라 반환(return)이라는 개념 자체가 없다.
 4) 파라미터는 일반 메소드와 동일하게 사용할 수 있다. 메소드 오버로딩(overloading)이 가능하다.(생성자를 여러 개 만들 수 있다.)
  • 생성자를 안 만들면 Java가 만든 "디폴트 생성자"가 사용된다.

‣ 디폴트 생성자(default constructor)

  • 개발자가 생성자를 하나도 만들지 않는다면 Java가 자동으로 만드는 생성자이다.

  • 파라미터가 없고, 본문이 비어있다.

  • 기본 필드값(0, 0.0, false, null)을 가진 객체를 생성할 때 사용한다.


▾ 생성자 활용 예시

컴퓨터 클래스

  // 생성자 (생성자는 일반적으로 필드 밑에 만든다.)
  public Computer() {
    System.out.println("Computer() 생성자가 호출되었다.");
  }
 
  public Computer(String model) {   // 생성자에서도 Setter처럼 필드에 값을 저장할 수 있다. (생성할 때 Setter까지 같이 쓰고 싶으면 생성자를 만들면 된다.)
    System.out.println("Computer(String model) 생성자가 호출되었다.");
    this.model = model;
  }

메인 클래스

    // Computer myCom 객체 선언
    Computer myCom;
   
    // Computer myCom 객체 생성
    myCom = new Computer();   // public Computer(){} 생성자가 호출된다. (인수 없음, 파라미터 없음)

    // Computer yourCom 객체 선언
    Computer yourCom;
   
    // Computer yourCom 객체 생성
    yourCom = new Computer("macbook");  // public Computer(String model){} 생성자가 호출된다.(인수 있음, 파라미터 있음)
   
    System.out.println("yourCom: " + yourCom.getModel());

‣ 인스턴스와 인스턴스 멤버


‣ 인스턴스(instance)

  • 메모리에 로드된 객체이다.

  • new 키워드를 이용해서 인스턴스를 생성할 수 있다.


‣ 인스턴스 멤버(instance member)

  • 인스턴스가 사용할 수 있는 멤버(필드, 메소드)이다.

  • 인스턴스가 호출할 수 있다.


‣ 클래스 멤버(class member)

  • 정적 멤버(static member)를 의미한다.

  • static 키워드가 추가된 멤버(필드, 메소드)이다.

  • 인스턴스가 생성되기 이전에(객체를 만들기 전, new 이전)사용할 수 있다.

  • 클래스 멤버는 인스턴스 생성 이전에 미리 메모리에 로드된다.

  • 클래스마다 1개씩만 메모리에 로드된다. (모든 인스턴스가 공유할 수 있다.)

  • 클래스를 이용해서 호출한다. (인스턴스를 만든 후 인스턴스로 호출할 수도 있지만 권장하지 않는다.)

  • 클래스 멤버는 다른 클래스 멤버에서 참조될 수 있다.


▾ static 활용 예제

MyMath 클래스

public class MyMath {
  // static 필드
  private static double PI;
 
  // static 필드 초기화를 위한 static 블록
  static {
    PI = 3.14;
  }
 
  // static 메소드
  public static double getCircleArea(double radius) {
    return PI * radius * radius;
  }
}
  • 클래스를 통해 부르는건 모두 클래스 멤버이다. 기울어져서 표현된다.

메인 클래스

  public static void main(String[] args) {
   
    // 원 반지름
    double radius = 1.0;
   
    // 원 넓이 구하기
    double circleArea = MyMath.getCircleArea(radius);
    System.out.println(circleArea);
  }

하! 너무 재미쒀~!

profile
개발이 세상에서 제일 재밌어요

3개의 댓글

comment-user-thumbnail
2023년 7월 20일

글 잘 봤습니다, 감사합니다.

답글 달기
comment-user-thumbnail
2023년 7월 26일

짤 언니랑 우리같다~~!!

1개의 답글

관련 채용 정보