자바 클래스 관련

이정민·2021년 10월 17일
0

단일 상속(single inheritance)

Java는 단일 상속만을 허용한다.
비중이 높은 클래스 하나만 상속관계로, 나머지는 포함관계로 한다.

class Tv {
   boolean power;
   int channel;
   
   void power() { power = !power; }
   void channelUp() { ++channel; }
   void channelDown() { --channel; }
}

class VCR {
   boolean power;
   int counter = 0;
   void power() { power = !power; }
   void play() { }
   void stop() { }
   void rew() { }
   void ff() { ]
}
--------------------------------------

class TVCR extends Tv {
   VCR vcr = new VCR();
   int counter = vcr.counter;
   
   void play() {
      vcr.play();
   }
   
   void play() {
      vcr.play();
   }
   
   void stop() {
      vcr.stop();
   }
   
   void ff() {
      vcr.ff();
   }
}

오버라이딩(overriding)

조상클래스로부터 상속받은 메서드의 내용을 상속받는 클래스에 맞게 변경하는 것을 오버라이팅이라고 한다.

-> 오버로딩(overloading) - 기존에 없는 새로운 메서드를 정의하는 것(new)
-> 오버라이딩(overriding) - 상속받은 메서드의 내용을 변경하는 것(modify)

  • override ~위에 덮어쓰다.
class Point {
   int x;
   int y;
   
   String getLocation() {
      return "x :" + x + ", y :" + y;
   {
}

class Point3D extends Point {
   int z;
   String getLocation() {
      return "x :" + x + ",y :" + y + ",z :" + z;
   }
}

오버라이딩의 조건

  1. 선언부가 같아야 한다.(이름, 매개변수, 리턴타입)
  2. 접근제어자를 좁은 범위로 변경할 수 없다.
    (조상의 매서드가 protected라면, protected, public 같은 같거나 더 큰 범위로만 변경할 수 있다.)
  3. 조상클래스의 메서드보다 많은 수의 예외를 선언할 수 없다.
    (조상클래스에 선언되어 있지 않은 예외도 선언할 수 없다.)


오버라이딩 super 이용

class Point {
   int x;
   int y;
   
   String getLocation() {
      return "x : " + x + ", y : " + y;
   }
}

class Point3D extends Point {
   int z;
   
   String getLocation() {
      //return "x : " + x + ", y : " + y + ", z : " + z;
      return super.getLocation() + ", z : " + z;
   }
}

super.getLocation()을 통해 조상클래스 메서드를 호출하는 것이 좋다.
(코드의 재사용성을 높이고, 조상코드가 바껴도 자동으로 변경되기 때문에)



super()

super() - 조상의 생성자

class Point {
  int x;
  int y;
  
  Point(int x, int y) {
     this.x = x;
     this.y = y;
  }
  //생략
}

class Point3D extends Point {
   int z;
   
   Point3D(int x, int y, int z) {
      this.x = x;
      this.y = y;
      this.z = z;
   }
   //생략
}

class PointTest {
   public static void main(String args[]) {
      Point3D p3 = new Point3D(1,2,3);
   }
}
// 에러 발생 !!

// 해결 방법 1
Point() {} //기본생성자 생성

// 해결 방법 2
Point3D(int x, int y, int z) {
   super(x,y);
   this.z = z;
} //super 이용
profile
안녕하세요.

0개의 댓글