๐ super์ super()
1. super : ์์ ์ด ์์๋ฐ์ ๋ถ๋ชจ๋ฅผ ๊ฐ๋ฆฌํค๋ ์ฐธ์กฐ ๋ณ์
super๋ ๋ถ๋ชจ ํด๋์ค๋ก๋ถํฐ ์์๋ฐ์ ํ๋๋ ๋ฉ์๋๋ฅผ ์์ ํด๋์ค์์ ์ฐธ์กฐํ๋ ๋ฐ ์ฌ์ฉํ๋ ์ฐธ์กฐ ๋ณ์์ด๋ค.
์์๊ณผ ๋ถ๋ชจ์ฌ์ด์ ๊ตฌ๋ถ์ด ์์ด์ผํ๋๋ฐ, ๋ฉค๋ฒ๋ณ์์ ์ง์ญ๋ณ์์ ์ด๋ฆ์ด ๊ฐ์ ๋ this๋ฅผ ๋ถ์ฌ์ ๊ตฌ๋ณํ๋ค.
์ด์ ๊ฐ์ด ์์๋ฐ์ ์์ ๋ฉค๋ฒ์ ๋ถ๋ชจ์ ๋ฉค๋ฒ๊ฐ ์ด๋ฆ์ด ๊ฐ์ ๋ super๋ฅผ ๋ถ์ฌ์ ๊ตฌ๋ถํ ์ ์๋ค.
๋ํ static๋ฉ์๋(class ๋ฉ์๋)๋ ์ธ์คํด์ค์ ์ ํ ๊ด๋ จ์ด ์๋ค, ๊ทธ๋ ๊ธฐ์ this์ ๋ง์ฐฌ๊ฐ์ง๋ก super ์ญ์ static๋ฉ์๋์์๋ ์ฌ์ฉ ํ ์ ์๊ณ ์ธ์คํด์ค ๋ฉ์๋์์๋ง ์ฌ์ฉ ํ ์ ์๋ค.
์กฐ์ ํด๋์ค์ ์ ์ธ๋ ๋ฉค๋ฒ ๋ณ์์ ๊ฐ์ ์ด๋ฆ์ ๋ฉค๋ฒ ๋ณ์๋ฅผ ์์ ํด๋์ค์์ ์ค๋ณตํด์ ์ ์ํ๋ ๊ฒ์ด ๊ฐ๋ฅํ๋ฉฐ ์ฐธ์กฐ ๋ณ์ super๋ฅผ ์ด์ฉํด์ ์๋ก ๊ตฌ๋ณํ ์ ์์ต๋๋ค.
class Parent {
int a = 10;
}
class Child extends Parent {
void display() {
System.out.print(a);
System.out.print(this.a);
System.out.print(super.a);
}
}
public class Inheritance02 {
public static void main(String[] args) {
Child ch = new Child();
ch.display();
}
}
// ์คํ๊ฒฐ๊ณผ
// 101010
์์ ์์ intํ ๋ณ์ a๋ ๋ถ๋ชจ ํด๋์ค์ธ Parent ํด๋์ค์์๋ง ์ ์ธ๋์ด ์๋ค.
๊ทธ๋ฌ๋ฏ๋ก ์ง์ญ๋ณ์ a์ this ์ฐธ์กฐ๋ณ์, super ์ฐธ์กฐ ๋ณ์ ๋ชจ๋ ๋ค ๊ฐ์ ๊ฐ์ ์ถ๋ ฅํ๋ค.
2. super() ๋ฉ์๋ : ์์ ์ด ์์๋ฐ์ ๋ถ๋ชจ์ ์์ฑ์๋ฅผ ํธ์ถํ๋ ๋ฉ์๋
this()์ ๋ง์ฐฌ๊ฐ์ง๋ก super() ์ญ์ ์์ฑ์์ด๋ค. ๋ถ๋ชจ ํด๋์ค์ ์์ฑ์๋ฅผ ํธ์ถํ ๋ ์ฌ์ฉํ๋ค.
์์ ํด๋์ค์ ์ธ์คํด์ค๋ฅผ ์์ฑํ๋ฉด, ํด๋น ์ธ์คํด์ค์๋ ์์ ํด๋์ค์ ๊ณ ์ ๋ฉค๋ฒ๋ฟ๋ง ์๋๋ผ ๋ถ๋ชจ ํด๋์ค์ ๋ชจ๋ ๋ฉค๋ฒ๊น์ง๋ ํฌํจ๋์ด ์๋ค. ๋ฐ๋ผ์ ๋ถ๋ชจ ํด๋์ค์ ๋ฉค๋ฒ๋ฅผ ์ด๊ธฐํํ๊ธฐ ์ํด์๋ ์์ ํด๋์ค์ ์์ฑ์์์ ๋ถ๋ชจ ํด๋์ค์ ์์ฑ์๊น์ง ํธ์ถํด์ผ๋ง ํ๋ค.
Objectํด๋์ค๋ฅผ ์ ์ธํ ๋ชจ๋ ํด๋์ค์ ์์ฑ์๋ ์ฒซ ์ค์ ๋ฐ๋์ ์์ ์ ๋ค๋ฅธ ์์ฑ์ ๋๋ ์กฐ์์ ์์ฑ์๋ฅผ ํธ์ถํด์ผ ํ๋ค.
๋ง์ฝ ๊ฐ๋ฐ์๊ฐ ์ง์ ์ถ๊ฐํ์ง ์๋๋ค๋ฉด ์ปดํ์ผ๋ฌ๊ฐ ์๋์ผ๋ก ์์ฑ์์ ์ฒซ ์ค์ 'super();'๋ฅผ ์ถ๊ฐํด์ค๋ค.
ํ์ง๋ง, ์ปดํ์ผ๋ฌ๊ฐ ํญ์ super()๋ฅผ ์๋ ์ถ๊ฐํด์ฃผ๋ ๊ฒ์ ์๋๋ค.
์๋ ์์ ์ฒ๋ผ ๋ถ๋ชจํด๋์ค์ ๊ธฐ๋ณธ ์์ฑ์๊ฐ ์๋ ๋งค๊ฐ๋ณ์๋ฅผ ๊ฐ์ง๋ ์์ฑ์๊ฐ ์๋ค๋ฉด ์๋์ผ๋ก ์ถ๊ฐ๋์ง ์๋๋ค.
class Parent{
int a;
Parent(int n){
a=n;
};
}
์ด๋ฐ ๊ฒฝ์ฐ์๋, ๋งค๊ฐ๋ณ์๋ฅผ ๊ฐ์ง๋ ์์ฑ์์ ๋ง์ถฐ super()์ ์ธ์๋ฅผ ๋ง์ถฐ์ฃผ๋ฉด ๋๋ค.
class Parent{
int a;
Parent(int n){
a=n;
};
}
class Child extends Parent(){
int b;
Child(){
super(40);
b=20;
}
}
'โค๏ธ JAVA > Basic' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JAVA] ์์ธ๋?(Exception) (0) | 2024.10.24 |
---|---|
[JAVA] this์ this() (0) | 2024.10.22 |
[JAVA] ์์(Inheritance) (0) | 2024.10.20 |
[JAVA] ์ ์ด์(modifier) (0) | 2024.10.18 |
[JAVA] ์์ฑ์(consructor) (0) | 2024.10.17 |