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
๋ฉ์ธ ๋ฉ์๋ ํธ์ถ -> ๋ถ๋ชจ ์์ฑ์ ํธ์ถ -> ์์ ์์ฑ์ ํธ์ถ ์์ผ๋ก ํ๋ก๊ทธ๋จ์ด ์คํ