자바 - super키워드의 마지막 장입니다.
super 키워드의 총 3개가지 쓰임새를 알아봤었는데요.
1) super키워드를 이용해서 부모클래스 객체의 변수를 참조하고자할때
2) super키워드를 이용하여 부모클래스의 메소드를 실행하고자할떄
3) super 키워드는 부모클래스의 생성자를 호출하는데 사용됩니다.
3) super 키워드는 부모클래스의 생성자를 호출하는데 사용됩니다.<<
자 이제 시작해보죠,
package super_keyword;
public class SuperTest03 {
public static void main(String[] args) {
Dog3 d3 = new Dog3();
}
}
// 여러분이 머릿속으로 컴파일하였을때의 실행값은 어떨거같나요?
class Animal03{
//Animal03-Con
Animal03(){
System.out.println("Animal03 is created");
}
}
// 이전 예제들과의 중복을 피하기위해 Animal03이라는 부모가 될 클래스를 생성하고
생성자를 줍니다.
class Dog3 extends Animal03{
//Dog-Con
Dog3(){
super();
System.out.println("Dog is created");
}
}
//위와 동일합니다.
그리곤 SuperTest03을 통해 실행시켜보기로하죠.

네 맞습니다.
Dog3(){
super();
System.out.println("Dog is created"); }
우리는 Dog3생성자에서 super(); 를 먼저 썻기때문에
우리는 컴파일러한테
" 야 컴파일러야 내가 Dog3 클래스에 생성자를 니가 자동으로 만들어주지만,
이번엔 내가 따로 명시해서 만들거야. 근데, super();를 넣을거야
무슨 말인지 알지?"
뭐 대충 이런 뜻입니다.
쉽지요?ㅎㅎㅎㅎㅎㅎ
super()나 this()가 명시되지않았다면, 컴파일러는 자동으로 각 클래스의 생성자에 super()를 자동으로 삽입합니다. 허나, 우리가 못볼뿐!

이번에는 우리가 명시해줬던 super(); 키워드를 빼고!

기본으로 Dog클래스의 객체만 만들어서 실행해봅시다.

잉?! 결과가 똑같네요.
그말인 즉슨 우리가 명시를 하든안하든 컴파일러는 자동으로 명시해준단 말이죠.
다만 에디터에서 안보일 뿐이랍니다.!
그럼 주로 쓰이는 super 키워드의 형태를 한번 알아볼까요?
package super_keyword;
public class SuperTest04 {
public static void main(String[] args) {
EMP emp = new EMP(1, "신입", 2200f);
emp.display();
}
}
class person{
int id;
String name;
person(int id, String name){
this.id = id;
this.name = name;
}
}
class EMP extends person{
float salary;
EMP(int id, String name , float salary){
super(id,name); // 부모의 생성자를 재사용!
this.salary = salary;
}
void display(){
System.out.println("id = " + id + ", name = " + name + ", salary = " + salary);
}
}

부모클래스가 될 person 클래스를 만들고
필드와 생성자를 만들어줍니다.
person(int id, String name){
this.id = id;
this.name = name;
} 여기서 this.를 주는 이유는 person클래스 내의 id를 사용하는거니까
헷갈려하지마 컴파일러야~ 라고 알려주는 겁니다.
this.를 안붙히면 이클립스는 int id라는 다른 변수를 생성해버리기 때문에
결론적으론 두개의 id가 person클래스 내의 존재하게되는겁니다.
물론 스코프 범위가 다르기 때문에 서로의 충동들 없습니다.
class EMP extends person{
float salary;
EMP(int id, String name , float salary){
super(id,name); // 부모의 생성자를 재사용!
// 코드의 중복을 최소화시키는 것을 늘 고려하기 때문에,
//우리는 EMP에서 다시 새로운 변수를 만들지않았습니다.
this.salary = salary;
}
void display(){
System.out.println("id = " + id + ", name = " + name + ", salary = " + salary);
} 어떤값이 나오나 한번 출력해보도록 하죠.

보신바와 같이 id, name은 부모클래스의 필드값들입니다.
코드의 중복을 최소화하고, 손쉽게 재사용할 수 있으며 다형성을 유지하기 위해서
좀 과장해서말하면 완소키워드라고 할 수 있겠습니다 ㅎㅎㅎ
RECENT COMMENT