2013. 7. 25. 16:48


■ extends

 : 부모의 모든 멤버를 상속받는다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Parent
{
    String str = "부모멤버";
    public void show()
    {
        System.out.println("부모의 메서드");
    }
}
 
class Child extends Parent
{
    String str = "자식멤버";
    @Override
    public void show()
    {
        System.out.println(super.str);
        System.out.println(this.str);
         
        super.show(); //부모의 메서드, 즉 재정의 하기 전의 메서드를 의미함.
        //this.show();  //무한재귀호출
    }
}
 
new Child().show()
 
부모멤버
자식멤버
부모의 메서드

 

 

 

부모가 있는 클래스에 한해서 super 키워드를 사용할 수 있는데

super는 부모를 의미하는 것이 맞지만 때에 따라선 자식 멤버를 가르키기도 한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Parent
{
    String str = "부모멤버";
}
 
class Child extends Parent
{
    public void show()
    {
        str = "자식이 재정의 한 멤버변수";
        String str = "지역변수";
         
        System.out.println(str);
        System.out.println(this.str);
        System.out.println(super.str);
    }
}
 
new Child().show()
 
지역변수
자식이 재정의 한 멤버변수
자식이 재정의 한 멤버변수

 

 

 부모클래스에 추상클래스가 존재한다면 해당 메서드는 반드시 재정의 해야한다. (하지 않은경우 컴파일 에러 발생)

 

1
2
3
4
5
6
7
8
9
10
11
abstract class Parent
{
    abstract void print();
    public void show() { }
}
 
class Child extends Parent
{
    @Override
    void print() { }
}

 

 

 

스태틱 메서드는 재정의 할 수 없다. 하지만 접근은 가능

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Parent
{
    public static void stM()
    {
        System.out.println("ㅎㅇ");
    }
}
 
class Child extends Parent
{
    public void show()
    {
        stM();
    }
}

 

 


 

■ implements

 : 인터페이스를 구현(구상화)한다.

 : 구현클래스는 인터페이스의 멤버를 반드시 재정의해야한다. 단, 파이널스태틱 멤버는 제외

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
interface I_Parent
{
    String str = null;
        //final static str = null;
        //인터페이스의 멤버 변수는 자동으로 파이널스태틱 변수로 선언됨.
     
    public void result();
    public void excute();
}
 
class Child implements I_Parent
{
    @Override
    public void result() { }
 
    @Override
    public void excute() { }
}

 

 

extends와 implements는 둘 다 상속의 개념이다.

하지만 클래스는 클래스끼리 extends 해야하며 인터페이스 역시 인터페이스끼리 extends 해야함.

implements 는 오직 인터페이스를 구현하는 클래스에만 해당된다.

class Parent { }

class Child extends Parent { }

 

interface I_Parent { }

interface I_Child extends I_Parent { }

 

interface I_Parent { }

class Child implements I_Parent { }

 



■ UpCasting

 : 부모형의 변수에 자식의 인스턴스를 할당할 시

 : 재정의 된 멤버에 한해서 자식의 멤버가 실행우선권을 갖는다. 하지만 보이는것은 부모것

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Parent
{
    public void show()
    {
        System.out.println("부모 메서드");
    }
}
 
 
class Child extends Parent
{
    @Override
    public void show()
    {
        System.out.println("자식 메서드");
    }
}
 
Parent p = new Child();
p.show();

 

 

'java' 카테고리의 다른 글

Enumeration, 열거형  (0) 2013.07.25
Generic, 제네릭  (0) 2013.07.25
팩토리얼(재귀호출)  (0) 2013.07.25
Args, 비정형인자  (0) 2013.07.25
연산자 우선순위  (0) 2013.07.25
Posted by 1+1은?