πŸ—„οΈ Backend/Java

μžλ°”(Java) - 객체 μ§€ν–₯ ν”„λ‘œκ·Έλž˜λ° (8) super, super()

kongmi 2023. 1. 16. 19:28

super

μžμ‹ ν΄λž˜μŠ€κ°€ λΆ€λͺ¨ 클래슀둜 λΆ€ν„° 상속 받은 ν•„λ“œ(멀버)λ₯Ό μ°Έμ‘°ν•˜λŠ” λ³€μˆ˜
클래슀 λ‚΄μ˜ λ©€λ²„λ³€μˆ˜μ™€ μ§€μ—­λ³€μˆ˜μ˜ 이름이 같을 경우 ꡬ뢄을 μœ„ν•΄ this. λ₯Ό μ‚¬μš©ν•˜λ“―μ΄
λΆ€λͺ¨ ν΄λž˜μŠ€μ™€ μžμ‹ 클래슀 μƒμ„±μžλ₯Ό κ΅¬λΆ„ν•˜κΈ° μœ„ν•΄ μ‚¬μš©!
import λ‹€ν˜•μ„±μ‘μš©1_0116.Product;

public class SuperFieldEx1 {
    public static void main(String[] args) {
        ChildEx childex = new ChildEx();
        childex.childMethod();
    }
}
class ParentEx {
    int x = 10;
}

class ChildEx extends ParentEx {
    int x = 20;

    void childMethod() {
        System.out.println("x = " + x);
        System.out.println("this.x = " + this.x);
        System.out.println("super.x = " + super.x);
    }
}

super()

λΆ€λͺ¨ 클래슀의 μƒμ„±μžλ₯Ό ν˜ΈμΆœν•˜λŠ” λ©”μ†Œλ“œ (μžμ‹μ˜ μƒμ„±μž λ‚΄μ—μ„œ 호좜)
μžμ‹μ˜ μƒμ„±μžμ—μ„œ λΆ€λͺ¨μ˜ μƒμ„±μžλ₯Ό ν˜ΈμΆœν•  λ•ŒλŠ” λ°˜λ“œμ‹œ!!! λΆ€λͺ¨μ˜ μƒμ„±μžλ₯Ό λ¨Όμ € ν˜ΈμΆœν•˜κ³  λ‹€λ₯Έ μ΄ˆκΈ°ν™” μ§„ν–‰
μƒμ„±μžλ₯Ό λ”°λ‘œ λ§Œλ“€μ§€ μ•ŠμœΌλ©΄ κΈ°λ³Έ μƒμ„±μžκ°€ ν˜ΈμΆœλ˜λŠ” 것 처럼...
λΆ€λͺ¨μ˜ μƒμ„±μžλ₯Ό λ³„λ„λ‘œ λ§Œλ“€μ–΄μ£Όμ§€ μ•ŠμœΌλ©΄ 기본적으둜 λΆ€λͺ¨μ˜ μƒμ„±μžκ°€ μžλ™ 호좜됨.

Parent

class Parent {
    int a;
    Parent() {
        System.out.println("λΆ€λͺ¨μ˜ κΈ°λ³Έ μƒμ„±μž 호좜");
        a = 10;
    }
    Parent(int n) {
        System.out.println("λΆ€λͺ¨μ˜ μƒμ„±μž 호좜");
        a = n;
    }

}

Child

class Child extends Parent {
    int b;
    Child() {
        super(200); // superλŠ” μžμ‹ μƒμ„±μžκ°€ μ‹€ν–‰λ˜κΈ° 전에 ν˜ΈμΆœν•΄μ•Ό 함.!!!!!!
        System.out.println("μžμ‹μ˜ μƒμ„±μž 호좜");
        b = 20;
    }
    void display() {
        System.out.println(a);
        System.out.println(b);
    }
}

Main

public class SuperField {
    public static void main(String[] args) {
        System.out.println("main λ©”μ†Œλ“œ 호좜");
        Child child = new Child();
        child.display();

    }
}

 

<좜λ ₯ν™”λ©΄>
main λ©”μ†Œλ“œ 호좜
λΆ€λͺ¨μ˜ μƒμ„±μž 호좜
μžμ‹μ˜ μƒμ„±μž 호좜
200
20
메인 λ©”μ†Œλ“œ 호좜 -> λΆ€λͺ¨ μƒμ„±μž 호좜 -> μžμ‹ μƒμ„±μž 호좜 순으둜 ν”„λ‘œκ·Έλž¨μ΄ μ‹€ν–‰