JAVA

상속, Inheritance

웹개발자준비 2018. 7. 25. 18:59

상속, Inheritance

-상속(Inheritance)이란 말 그대로 '부모의 유산을 물려받다'를 의미하고 이는 '자식이 부모의 것을 가진다'라고 할 수 있습니다.

 객체 지향 프로그래밍에서도 이와 비슷한 개념으로 쓰이는데, 여기에서는 부모 클래스에 정의된 멤버를 자식 클래스가 물려받는 것을 말합니다.


- 클래스와 클래스간에 발생

- 부모 클래스가 가지고 있는 모든 멤버(변수,메소드)를 자식 클래스에게 물려줌

- 왜 하는지?

1. 코드 재사용


상속 관계에 있는 클래스

- 상속 관계에 있는 클래스

- 부모클래스 <-> 자식클래스

- 슈퍼클래스 <-> 서브클래스

- 기본클래스 <-> 확장(파생)클래스


*상황] 담당 업무 > 난수 발생 잦음 > Random 객체 사용 빈도 높음

1. nextInt() : -21억~21억

2.1~10 사이의 난수

3.색상 난수 : red, yellow, blue, orange,green



//test1

public static void test1(){

Random rnd = new Random();


/1.

System.out.println(rnd.nextInt());


/2.

System.out.println(rnd.nextInt(10)+1);


/3

String[] color = new String[] {"red", "yellow", "blue", "orange", "green"};

System.out.println(rnd.nextInt(color.length));

}


//MyRandom 클래스에 상속사용

public class MyRandom extends Random{


private Random rnd; //멤버변수

private String[] color[];


public MyRandom() { //기본 생성자

this.rnd = new Random();

this.color = new String[] {"red", "yellow", "blue", "orange", "green"};

}


public int nextSmallInt(){

return rnd.nextInt(10)+1;

}


public String nextColor(){

return color[rnd.nextInt(color.length)];

}

}


//test2 - MyRandom 객체 선언하여 쉽게 출력.

public static void test2(){


MyRandom random = new MyRandom();


System.out.println(random.nextInt());


System.out.println(random.nextSmallInt());


System.out.println(random.nextColor());


}


**추가**

1. 상속에서 메소드 오버라이딩을 하면 외부에선 자식의 메소드만 호출이 가능하다.

- 외부에서 부모의 메소드를 호출하고 싶으면 어떻게?

- 외부에서는 부모의 메소드를 직접 호출 불가능 -> 간접 호출 가능(자식 클래스를 통해서..)


2. 메소드 오버라이딩

//main

MyChild c = new MyChild();

//c.a = 10;

//c.aaa();


//c.aaa();

//c.a = 10;


c.a=10;

c.aaa(); //parent.aaa -> child.aaa <부모와 자식 메소드 충돌이 일어나면 100프로 자식 메소드만 사용할수 있다.>

c.ccc(); // 부모의 aaa()


class MyParent {

public int a = 100;

private int b = 200;

public void aaa() {

System.out.println("aaa");

}

private void bbb() {

System.out.println("bbb");

}

}


class MyChild extends MyParent {

//변수 오버라이드(X) + 구현 하지 않는 코드

//public int a;

//메소드 오버라이드

public void aaa() {

System.out.println("AAA");

}

public int c=30;

private int d=40;

public void check() {

System.out.println(this.c);

System.out.println(this.d);

System.out.println(this.a);

//System.out.println(this.b);

}

public void ccc() {

//외부에서 ccc() 호출하면 부모의 aaa() 호출하기 위한 도구(위임)

//aaa();

//this.aaa(); //this : 나 자신(현재 객체)

super.aaa(); //super : 부모 객체, super 키워드는 주로 자식 클래스에서 부모의 멤버를 접근할 때 사용(메소드 오버라이드에 의해서 감춰진 멤소드를 접근할때)

}

@Override

public String toString() {

// return super.toString();

return "테스트";

}

}


출처: http://blog.eairship.kr/116 [누구나가 다 이해할 수 있는 프로그래밍 첫걸음]