Backend/JAVA

[JAVA] super

howdyoon 2023. 3. 21. 00:24

super 부모, 조상
superclasses 부모클래스들
subclassed 자식클래스들

super   : 자식클래스에서 부모클래스의 멤버에 접근할 때
super() : 자식클래스의 생성자함수가 부모 클래스의 생성자함수를 호출할때 

this   : 멤버변수(field)와 일반 지역변수를 구분하기 위해
this()  : 자신의 생성자함수가 자신의 생성자함수를 호출할 때

 

상속관계에서 생성자 함수 호출 순서
- 부모생성자가 먼저 호출되고 자신의 생성자 함수가 호출된다

 

[ School 클래스 생성 후 실습 ]

package oop0320;

public class Test04_super {

	public static void main(String[] args) {

		//School() -> MiddleSchhol()
		MiddleSchool ms=new MiddleSchool();
		ms.disp();
		
		//School() -> HighSchhol()
		HighSchool hs=new HighSchool();
		hs.disp();

	}//main() end
}//class end

[ School 클래스 ]

package oop0320;

class School extends Object{
	String name="학교";
	public School() {
		System.out.println("School()...");
	}
}//class end

class MiddleSchool extends School {
	public MiddleSchool() {
		//상속관계에서 부모 생성자 함수 호출 명령어
		super(); //생략가능하다
		
		System.out.println("MiddleSchool()...");
	}
	
	public void disp() {
		System.out.println(name); //학교. 부모가 물려준 값 그대로 
	}
}//class end

class HighSchool extends School {
	String name="고등학교";
	
	public HighSchool() {
		super();
		System.out.println("HighSchool()...");
	}
	
	public void disp() {
		String name="강남 고등학교";
		System.out.println(name);	   //강남고등학교 지역변수
		System.out.println(this.name); //고등학교	  나의 멤버변수
		System.out.println(super.name);//학교      부모의 멤버변수
	}
}//class end

super, super()와 this, this() 활용한 클래스 설계

[ Parent 클래스 생성 후 실습 ]

package oop0320;

public class Test05_super {

	public static void main(String[] args) {

		Child child=new Child(10, 20, 30);
		System.out.println(child.three);
		System.out.println(child.one);
		System.out.println(child.two);

	}//main() end
}//class end

[ Parent 클래스 ]

package oop0320;

class Parent extends Object{
	int one, two;
	public Parent() {}
	public Parent(int one, int two) {
		this.one=one;
		this.two=two;
	}
}//class end

class Child extends Parent {
	int three;
	public Child() {
		super(); //생략가능
	}
	public Child(int a, int b, int c) {
		
		//주의) one, two멤버변수가 private속성이면 에러발생
		//super.one=a;
		//super.two=b;
		
		//상속받은 멤버변수(one, two)에 초기값 전달
		super(a, b);
		this.three=c;
	}
}//class end