Backend/Java

[Java] 클래스

가은파파 2021. 1. 20. 11:16

# 클래스 정의하는 방법

객체지향 컨셉으로 아래 샘플로 각각 필드와 생성자, 메소드에 관해서 설명해보겠다.

public class Bicycle { 
         
    // the Bicycle class has 
    // three fields 
    public int cadence; 
    public int gear; 
    public int speed; 
         
    // the Bicycle class has 
    // one constructor 
    public Bicycle(int startCadence, int startSpeed, int startGear) { 
        gear = startGear; 
        cadence = startCadence; 
        speed = startSpeed; 
    } 
         
    // the Bicycle class has 
    // four methods 
    public void setCadence(int newValue) { 
        cadence = newValue; 
    } 
         
    public void setGear(int newValue) { 
        gear = newValue; 
    } 
         
    public void applyBrake(int decrement) { 
        speed -= decrement; 
    } 
         
    public void speedUp(int increment) { 
        speed += increment; 
    } 
         
} 


Bicycle의 하위 클래스에 seatHeight만 추가하여 클래스를 생성하였다.

public class MountainBike extends Bicycle { 
         
    // the MountainBike subclass has 
    // one field 
    public int seatHeight; 

    // the MountainBike subclass has 
    // one constructor 
    public MountainBike(int startHeight, int startCadence, 
                        int startSpeed, int startGear) { 
        super(startCadence, startSpeed, startGear); 
        seatHeight = startHeight; 
    }    
         
    // the MountainBike subclass has 
    // one method 
    public void setHeight(int newValue) { 
        seatHeight = newValue; 
    }    

} 


*클래스의 선언
public, private 해당 클래스의 접근에 대한 컴포넌트이다.
public : 모든 클래스에서 접근 가능하다.
private : 오직 해당 클래스에서만 접근 가능하다.

class의 첫글자는 대문자여야 한다. method는 동사(verb)여야 한다.
extends를 선언하며 parent 클래스를 상속 받을 수 있다.
implements를 선언하며 인터페이스를 받을 수 있다.

*클래스의 멤버변수
필드 : 클래스 안에 멤버변수(인스턴스 변수)
cf. 클래스 변수 : static이라는 예약어가 있는 변수
지역변수 : 블록코드 or 메소드 안에 변수
파라미터(매개 변수) : 메소드나 생성자에 넘겨주는 변수

ex)
public class VariableTypes{
  int instanceVariable;  //인스턴스변수
  static int classVariable; //클래스변수
  public void method(int parameter//매개변수) {
    int localVariable; //지역변수
  }
}


# 메소드 정의하는 방법

클래스의 매소드


public,private,protected

Access Levels 별로 접근 가능한 수준을 표로 정리한 것이다.

Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N

클래스 접근 관련 개발자 팁

 

  • 가장 제한적인 Modifier를 사용해라. 특정 멤버만 쓸 수 있게 private를 사용해라 특별한 다른 사유가 없다면.
  • public은 피하라. 왜냐하면 특정 실행문에 연결되고, 코드의 변화 유동성을 제한시키는 경향이 있다.

return타입 : void는 리턴값이 필요 없음.
method name, ( )사이에 파라미터(매개 변수), Exception 을 정의 가능.
{ } 사이에 메소드 코드, 지역 변수를 정의

오버라이딩 : 다양한 변수(파라미터)의 메소드를 만들기 위해 아래와 같이 오버라이딩이 가능하다.

public class DataArtist { 
  public void draw(String s){ } 
  public void draw(int i){ } 
  public void draw(double f){ } 
  public void draw(int i, double f){ } 
} 


컴파일러는 메서드를 구분할 때 반환 형식을 고려하지 않으므로 반환 유형이 다른 경우에도 동일한 시그니처의 두 메서드를 선언할 수 없습니다.

매소드, 파라미터에 관하여

파라미터 타입 : 기본형, 참조형 모든 타입이 가능.
public Polygon polygonFrom(Point... corners) {
}
varargs(점 세개)를 활용해서 다양한 타입의 파라미터 타입을 받을 수 있다.

 

 

메소드의 리턴 Value

 

메소드의 리턴타입은 메소드 선언부에 결정합니다. { } 바디 부분에서 return을 명시하여야 한다.

클래스 hierarchy

아래 예시처럼 리턴타입이 클래스의 계층구조, 오버라이딩이 가능하다.

public Number returnANumber() {
    ...
}
//위의 계층구조의 클래스라면 retrunANumber는 ImaginaryNumber로 return이 가능하다.

public ImaginaryNumber returnANumber() {
    ...
}
//위와 같이 오버라이딩이 가능하다.

 

# 생성자 정의하는 방법

public Bicycle(int startCadence, int startSpeed, int startGear) { 
    gear = startGear; 
    cadence = startCadence; 
    speed = startSpeed; 
} 


# 객체 만드는 방법 (new 키워드 이해하기)

매소드의 상호작용으로 객체가 만들어진다.
프로그램 내에서 객체의 라이프사이클에 대해서 알아보자. 이를 통해 객체가 종료되고 어떻게 시스템을 clean up될 수 있는지 알 수 있다.

Bicycle myBike = new Bicycle(30, 0, 8); // new를 통해 메모리 공간을 만든다.
new Bicycle(30, 0, 8);을 통해 2가지 작업이 진행된다.
1) new 키워드는 객체를 만드는 자바 operator 이다.
2) 생성자를 call하고 new 객체를 생성한다.

Bicycle myBike;
컴파일러에게 이름과 타입을 알려주는 작업이다. 기본형이라면 해당 변수 선언이 적절한 양의 메모리를 예약한다.
하지만 위처럼 참조형 타입이 선언되면, 객체가 실제로 생성되기 전까지 정의되지 않는다. 즉 참조형 변수 선언은 객체를 만들지 못한다.

 

new Bicycle(30, 0, 8);
그래서 위와 같이 참조형 타입 클래스는  new연산자에 의해 생성자를 불러야 한다. 모든 참조형 타입의 클래스는 1개 이상 생성자가 필요하다. 만약 1개도 선언하지 않는다면, 자바 컴파일러는 디폴트 생성자를 call한다. 디폴트 생성자는 parent의 no-argument생성자(parent가 없다면 Object의 생성자를 call)를 call한다. 그러므로 컴파일러가 reject없이 수행된다.(만약 parent가 생성자가 없을 시에 

클래스를 인스턴스화 하다 = 객체를 생성한다. 객체가 생성될 때 인스턴스 클래스가 생긴다. 그러므로 인스턴스화 된다고 한다.

 

Point originOne = new Point(23, 94);

public class Rectangle {
    public int width = 0;
    public int height = 0;
    public Point origin;

    // four constructors
    public Rectangle() {
        origin = new Point(0, 0);
    }
    public Rectangle(Point p) {
        origin = p;
    }
    public Rectangle(int w, int h) {
        origin = new Point(0, 0);
        width = w;
        height = h;
    }
    public Rectangle(Point p, int w, int h) {
        origin = p;
        width = w;
        height = h;
    }

    // a method for moving the rectangle
    public void move(int x, int y) {
        origin.x = x;
        origin.y = y;
    }

    // a method for computing the area of the rectangle
    public int getArea() {
        return width * height;
    }
}

각 생성자가 초기 변수, 각 기본형, 참조형 변수을 제공한다. 자바 컴파일러가 각 생성자의 타입과 변수에 따라 생성된다.

Rectangle rectOne = new Rectangle(originOne, 100, 200);

int height = new Rectangle().height;

1라인의 메모리 도식화

height는 Rectangle 참조형 타입의 클래스의 height의 디폴트 생성자를 바로 가져온다. 2라인의 케이스는 프로그램에 메모리가 JVM에 의해 쌓이지 않는다. 해당 객체는 참조되지 않는다.

 

*The Garbage Collector

객체지향 언어는 모든 객체가 유지되기를 요구하고, 필요없는 것들은 즉시 destroy되어야 한다. 자바 플랫폼은 걱정할 필요없다. 시스템이 원하는 만큼 많은 객체를 만들 수 있고, 알아서 destory시켜준다. JRE가 더이상 사용되지 않을 때, 객체를 삭제한다. 이것을 Garbage Collector라고 한다.

 

해당 개체에 대한 참조가 더 이상 없는 경우 개체가 가비지 수집을 수행할 수 있습니다.

 

  • 변수에 저장된 참조는 일반적으로 변수가 범위를 벗어날 때 삭제됩니다.  
  • 또는 변수를 특수 값 null로 설정하여 개체 참조를 명시적으로 삭제할 수 있습니다.
  • 프로그램은 동일한 개체에 대해 여러 개의 참조를 가질 수 있습니다. 개체에 대한 모든 참조는 개체가 가비지 수집을 위해 사용 가능하기 전에 삭제해야 합니다.

 

 

5.this 키워드 이해하기 

 

this는 인스턴스 매소드 or 생성자에서 현재 객체를 의미한다.

 

public class Circle { 
    private int x, y, radius; 
    public void setOrigin(int x, int y) { 
        this.x = x; //not x=x;
        this.y = y; //not y=y;
    } 
} 

클래스 멤버 (클래스 변수, 클래스 메소드)

  • 특징: 1.인스턴스 생성 이전부터 접근가능.
  • 특징: 2.인스턴스에 속하지 않음
public class Bicycle {
    // 객체의 인스턴스가 생성되었을때 객체 변수가 생성.    
    private int cadence;
    private int gear;
    private int speed;
    private int id;
    private static int numberOfBicycles = 0;
    //final 사용해 unchange 변수 지정
    static final double PI = 3.141592653589793;
        
    public Bicycle(int startCadence, int startSpeed, int startGear){
        gear = startGear;
        cadence = startCadence;
        speed = startSpeed;

        // Bicycle 객체 생성된 수 만큼
        // and assign ID number
        id = ++numberOfBicycles;
    }

    // new method to return the ID instance variable
    public int getID() {
        return id;
    }
        ...
}

 

자바 static 의 의미와 사용법

  • static 변수, 메서드: 인스턴스 생성 이전부터 접근가능. 인스턴스 변수, 메서드는 new 객체 생성 후에 호출 가능.

Static 변수, 메소드 설명

 

'Backend > Java' 카테고리의 다른 글

annotations  (0) 2021.02.06
Enum 자바의 열거형  (0) 2021.01.29
[Java] 선택문, 반복문  (0) 2021.01.18
Java 예외 처리 정리  (0) 2021.01.16
Junit5 문법 / 예제 / 활용 방법  (0) 2021.01.16