YSHUSH

Inheritance.2 본문

Coding/Java

Inheritance.2

코딩; 2021. 12. 16. 06:50

MainClass

public class MainClass {
	public static void main(String[] args) {
		
	//	Myclass cls = new Myclass();		
	//	Myclass cls1 = new Myclass(222, "홍길동");

	//	ChildClass cc = new ChildClass();	// 호출순서는 부모클래스가 먼저, 그다음 자식 클래스
		
		ChildClass cc1 = new ChildClass(11, "노지혜", 168.5);		
	}
}

 


MyClass

public class Myclass {
	
	private int number;
	private String name;
	
	public Myclass() {		// 기본 생성자
		this(0, "빈칸");		// this(); 는 생성자 맨 윗칸에 적어야 적용할 수 있다!
		
		System.out.println("Myclass() Myclass()");
	}

	public Myclass(int number, String name) {
	//	this();		// 기본 생성자
		
		this.number = number;
		this.name = name;
		System.out.println("Myclass Myclass(int number, String name)");		
	}	
}

 


ParentClass

public class ParentsClass {
	
	private int number;
	private String name;
	
//	public ParentsClass() {
//		System.out.println("ParentsClass() ParentsClass()");
//	}

	public ParentsClass(int number, String name) {

		this.number = number;
		this.name = name;
	}
}

 


ChildClass

public class ChildClass extends ParentsClass {

	private double height;

	public ChildClass() {
		super(123, "hello");	// super는 부모클래스의 생성자를 알려줌, 생성자 호출시 super와 혼용불가
		System.out.println("ChildClass() ChildClass()");
	}

	public ChildClass(double height) {
		super(234, "world");
		this.height = height;
	}
	
	public ChildClass(int number, String name, double height) {
		super(number, name);	// super도 맨 위에다 적어줘야 하고 생성자 호출시 this와 혼용불가능
		this.height = height;
	}
}

 

'Coding > Java' 카테고리의 다른 글

Over ride.2  (0) 2021.12.16
Over ride.1  (0) 2021.12.16
Inheritance.1  (0) 2021.12.16
숫자 정렬 예제  (0) 2021.12.15
Encapsule  (0) 2021.12.14