반응형

오버로딩 / 오버라이딩

오버로딩은 기존에 없는 새로운 메서드를 추가

오버라이딩은 조상으로부터 상속받은 메서드의 내용을 변경

 

super

자손 클래스에서 조상 클래스로부터 상속받은 멤버를 참조할때 사용

 

public class SuperTest {
    public static void main(String[] args) {
        Child c = new Child();
        c.method();
    }
}

class Parent{
    int x = 10;
}

class Child extends Parent{
    int x = 20;

    void method(){
        System.out.println("x=" + x);                // 20
        System.out.println("this.x=" + this.x);      // 20
        System.out.println("super.x=" + super.x);    // 10
    }
}

 

final

불변성을 가지도록 final 키워드를 제공

1. final 변수

final String str = "hello";

str = "hi" // error

2. final arguments

public void func(final int num){
	num = 2; //error
}

3. final class 

상속이 불가능하다.

final class Test{
	final String str = "hello";
}

class Test2 extends Test{
	//error
}

4. final method

override 불가능하다. (재정의 불가)

class Test{
	final String getTest(){}
}

class Test2 extends Test{
	@Override
    String getTest(){
    	//error
    }
}

다형성

 

public class BindingTest {
    public static void main(String[] args) {
        Parent p = new Child();
        Child c = new Child();

        System.out.println("p.x= " + p.x);
        p.method();

        System.out.println("c.x= " + c.x);
        c.method();
        
        // p.x= 100
        // c m
        // c.x= 200
        // c m
    }
}

class Parent{
    int x = 100;

    void method(){
        System.out.println("p m");
    }
}

class Child extends Parent{
    int x = 200;

    void method(){
        System.out.println("c m");
    }
}

 

필드와 메서드가 일치하지 않아서 위 결과에 대해서 전혀 이해가 안되었다.

알고보니 메서드는 인스턴스를 참조하고, 필드는 참조변수를 바라본다.

만약 자식클래스에 필드, 메서드 다 없다면? -> 부모 클래스에 필드와 메서드를 출력한다.

반응형