2022.11.17 JAVA 16일차 생성자2, 상속

2022. 11. 22. 14:09JAVA

생성자 

생성자에서 생성자를 호출하는법
this. : 해당클래스의 인스턴스 변수 호출 
this() : 생성자 호출

생성자 내에서 생성자를 호출할 시 무조건 첫번째 줄에 와야한다

 

class Car
{
	String color;
	String gearType;
	int door;
	
	Car()
	{
		this("white", "auto", 4);
	}
	
	Car(String color)
	{
		this(color, "auto",4);
	}
	
	Car(String color, String gearType)
	{
		this(color,gearType,2);
	}
	
	Car(String color, String gearType, int door)
	{
		this.color = color;
		this.gearType = gearType;
		this.door = door;
	}
	
}

public class MySample1117 {

	public static void main(String[] args) {
		
		//생성자
	
		Car c1= new Car();
		Car c2 = new Car("blue");
		
		System.out.println("c1의 color = " + c1.color + ", gearType = " + c1.gearType + ", door = " + c1.door);
		System.out.println("c2의 color = " + c2.color + ", gearType = " + c2.gearType + ", door = " + c2.door);		
	}

}

출력

 


상속
기존의 클래스를 재사용하여 새로운 클래스를 작성하는것
상속을 통해 부모 클래스가 가지고있는 모든것을(생성자 제외) 자식클래스가 물력받아 같이 공유하고 확장하는 개념
사용예 : class Chile exends Parent{ //.......... }

조상클래스 : 부모(parent)클래스, 상위(super)클래스, 기반(base)클래스
자손클래스 : 자식(child)클래스, 하위(sub)클래스, 파생된(derived)클래스

class Person2
{
	String name;
	String job;
	int age;

	Person2(String name, String job, int age)
	{
		this.name = name;
		this.job = job;
		this.age = age;
	}
	
	
	
}

class Student2 extends Person2
{
	int score;
	
	Student2(String name, String job, int age, int score) 
	{
		super(name,job,age);
		this.score = score;
	}
	
	void print()
	{
		System.out.println("이름 : " + name + ", 직업 : " + job + ", 나이 : " + age + ", 점수 : " + score);
	}
}

class Teacher2 extends Person2
{
	int pay;
	
	Teacher2(String name, String job, int age, int pay) 
	{
		super(name,job,age);
		this.pay = pay;
	}
	
	void print()
	{
		System.out.println("이름 : " + name + ", 직업 : " + job + ", 나이 : " + age + ", 급여 : " + pay);
	}
	
}




public class MySample1117_8 {

	public static void main(String[] args) {
		
		Student2 st = new Student2("홍길동", "학생회장", 19, 100);
		st.print();
		
		Teacher2 t = new Teacher2("펭수", "본부장", 30, 1000);
		t.print();
	}

}

출력

 

super(매개변수) : 부모클래스의 생성자를 호출(실행)