- 편의상 setter, getter 메소드는 생략했다.
매개변수가 1개인 경우
부모 클래스
public class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
}
- 부모 클래스 생성자에 name이 필요하다 : 인스턴스 생성 시 name을 받아야한다.
자식 클래스
public class Mammalia extends Animal{
public Mammalia(String name) {
super(name);
}
}
- 생성자 (public Mammalia(String name)) 는 메인 클래스에서 new 로 객체가 생성될 때 실행된다.
생성자 Constructor
- 클래스명과 메서드명이 동일해야 한다.
- 리턴 타입을 정의하지 않는다 (void 와 같은...)
- 자식 클래스 생성자에 name을 받고, 이는 부모 클래스의 변수임을 super()을 사용하여 표시한다.
메인 클래스
public class test {
public static void main(String[] args){
Mammalia cat = new Mammalia("happy");
}
}
- happy라는 매개변수와 함께 자식 클래스를 선언한다.
매개변수가 여러 개인 경우
부모 클래스
public class Animal {
private String name;
private int age;
public Animal(String name, int number) {
this.name = name;
age = number;
}
}
- name, age 라는 변수가 필요하다. 생성자에서 멤버변수에 변수를 넣어준다.
- name은 생성자의 매개변수와 멤버변수의 이름이 같으므로 this를 사용한다.
- age는 생성자의 매개변수와 멤버변수의 이름이 다르므로 this를 사용하지 않는다. ( 사용해도 무방하다. )
- age의 setter, getter는 부모 클래스에 위치한다.
자식 클래스
public class Mammalia extends Animal{
public Mammalia(String name, int number) {
super(name, number);
}
public void aging() {
age++;
}
}
- 자식 클래스의 생성자에서 name과 number를 받는다.
- 부모 클래스 생성시 필요한 값을 super에 넣어준다.
- 부모 클래스의 멤버변수들이므로 자식 클래스에서는 number의 setter, getter를 지정하지 않는다.
메인 클래스
public class test {
public static void main(String[] args){
test test = new test();
test.sayName("medium");
test.sayName("final");
Mammalia cat = new Mammalia("happy", 10);
System.out.println(cat.getName()); // happy
System.out.println(cat.getAge() + "살"); // 10살
cat.aging();
System.out.println(cat.getAge() + "살"); // 11살
}
}
- 자식 클래스로 인스턴스를 생성할 때, happy라는 name과 10라는 number을 지정한다.
- 부모 클래스의 메서드인 getName, getAge, aging 가 제대로 동작함을 볼 수 있다.
요약
- 메인 클래스에서 자식 클래스의 인스턴스를 선언할 때, 매개변수는
- 자식 클래스에서 받아서 부모 클래스의 변수임을 super로 알린다.
- 부모 클래스의 생성자에서 매개변수를 받아 멤버변수에 넣는다.