자바/정리
(JAVA)상속
acid7937
2022. 11. 10. 18:08
상속... 뭔가 느낌이 오질 않는가? 상속 받는다... 키야 기분이 좋다. 하지만 배우는 입장에서는 자바의 상속은 기분이 나쁘다. 지금 내 기분이 그렇다.
상속은 말 그대로 간단하게 A 클래스의 기능을 B 클래스에서 사용 가능하게 만드는것이다. 간단하다. 하지만 간단하지 않다... 뭔소리인지 알아보자.
class HCalculator {
int left, right;
public void enter(int left, int right) {
this.left = left;
this.right = right;
}
public void avg() {
System.out.println((this.left + this.right) / 2);
}
public void sum() {
System.out.println(this.left + this.right);
}
}
class subtract extends HCalculator
{
public void subtractable(){
System.out.println(this.left - this.right);
}
}
class multiply extends subtract
{
public void sum(){
System.out.println("실행결과는!!! 뚜둥 = " + (this.left +this.right));
}
public void multiplyalbe(){
System.out.println(this.left * this.right);
}
}
public class inherit {
public static void main(String[] args) {
HCalculator c1 = new HCalculator();
c1.enter(20,40);
c1.sum();
c1.avg();
subtract c2 = new subtract();
c2.enter(30,40);
c2.sum();
c2.avg();
c2.subtractable();
multiply c3 = new multiply();
c3.enter(20,40);
c3.sum();
c3.avg();
c3.subtractable();
c3.multiplyalbe();
}
}
실행 결과는 다음과 같다.
60
30
70
35
-10
실행결과는!!! 뚜둥 = 60
30
-20
800
지금 위에 코드는 부모인 HCalculator가 자식인 subtract을 낳고 subtract은 multiply를 낳는 과정이다. 그리고 부모의 특별한 능력은 자녀에게 손자에게 계속 이어져서 강력한 주인공을 만든다. 이렇게 말하니 간단해 보이지 않는가?
코드를 보면 부모인 HCalculator는 오직 더하기와 평균값 기능만 있고 자식인 subtract은 뺄셈 기능이 추가 되었다. 거기다 그 자녀인 multiply는 추가로 곱하기 기능까지 추가 되었다. 하지만 자식들은 부모의 기능을 온전히 물려받는다.
이게 상속의 기본 개념이다.
상속을 가져오는 방법은 Class 자기자신이름 extends 부모의이름 이다. 이러면 그냥 끝이다.
하지만...
상속을 생성자로 이야기를 하면 이야기가 달라진다. 이어서 작성 하도록 하겠다.
https://acid7937.tistory.com/18