728x90
728x90
= super (생성자, 메서드)
this와 같이 super. 과 super() 두가지로 구분할 수 있다.
super.은 부모클래스의 멤버를 참조할 수 있고.
super()는 생성자 내부에서만 사용이 가능하며, 부모클래스의 생성자를 호출하는데 사용합니다.
생성자의 첫 줄에 반드시 this().super()가 있어야한다.
하지만 실질적으로 기재되어있지 않다면, 묵시적으로 적혀잇는것으로 판단한다.
<정답>
누구로 생성하던 이문장을 실행
이름:홍길동, 나이:10 학번:20001212
누구로 생성하던 이문장을 실행
이름:이름미정, 나이:1
<해설>
< Mother >
package super_.basic;
public class Mother extends Person{
//생략
Mother(){
super();
}
}
< Student >
package super_.basic;
public class Student extends Person {
String studentId;
Student(String name, int age, String studentId){
// super();//문법 (person의 기본생성자를 의미)
// this.name=name;
// this.age=age;
super(name,age);
this.studentId=studentId;
}
String info() {
return super.info()+" 학번:"+studentId;
}
}
< Person >
package super_.basic;
public class Person {
String name;
int age;
Person(String name, int age){
this.name = name; //멤버변수 접근 어려움
this.age = age;
System.out.println("누구로 생성하던 이문장을 실행");
}
Person(String name){
this(name,1);
Person(){
this("이름미정",1);
String info() {
return "이름:"+this.name+", 나이:"+this.age;
}
}
< MainClass>
package super_.basic;
public class MainClass {
public static void main(String[] args) {
Student s = new Student("홍길동",10,"20001212");
System.out.println(s.info());
Mother m= new Mother();
System.out.println(m.info());
}
}
Mother부분을 보면, Person부분을 그대로 따른다는 것을 알 수 있다.
그래서 Mother부분의 출력값은 Person 클래스의 메소드를 사용해서 출력값이 나오게 된다.
728x90
'수업 복습하기 > Java' 카테고리의 다른 글
Day 11 - 캡슐화(Encapsulation) (0) | 2021.08.31 |
---|---|
Day 11 - 접근 제한자(Access Modifier) (0) | 2021.08.31 |
Day 11 - this() & this. (0) | 2021.08.30 |
Day 11 - 오버로딩 (Overloading) (0) | 2021.08.30 |
Day 10 - 오버라이딩(Overriding) (0) | 2021.08.30 |