부모 클래스로 부터 하위 클래스에게 멤버변수, 메소드를 물려주는 행위
한 번 만든 클래스 재사용·활용을 위하여
extends (확장·연장)
class 하위클래스 extends 상위클래스{ }
1) name(문자열) 멤버 변수를 가진 Person 클래스를 만드세요.
2) Person 클래스를 상속받는 Student 클래스를 만드세요. Student 클래스에는 studentId(정수) 멤버 변수를 추가하세요.
3) main 함수에서 Student 객체를 생성하고, 상속받은 name과 자신의 studentId에 값을 저장한 뒤 모두 출력하세요.
class Person {
String name;
}
class Student extends Person { // Person 클래스를 상속받는 Student 클래스
int studentID;
}
public class Practice {
public static void main(String[] args) {
Student student = new Student(); // Student 타입의 객체 생성
student.name = "홍길동";
// Student 클래스에서는 멤버변수를 선언하지 않았지만,
// 상위 클래스인 'Person'클래스의 멤버변수를 이용하여 name 속성을 정의
student.studentID = 10001;
// student 클래스 본연의 멤버변수
System.out.println("이름 : " + student.name + " 학번 : " + student.studentID);
// 출력 >> 이름 : 홍길동 학번 : 10001
}
}
1) "동물이 소리를 냅니다."를 출력하는 makeSound() 메소드를 가진 Animal 클래스를 만드세요.
2) Animal을 상속받고, makeSound() 메소드를 재정의하여 "고양이가 야옹하고 웁니다."를 출력하는 Cat 클래스를 만드세요.
3) main 함수에서 Cat 객체를 생성하고 makeSound() 메소드를 호출하여, 재정의된 내용이 출력되는지 확인하세요.
class Animal {
void makeSound() {
System.out.println("동물이 소리를 냅니다.");
}
}
class Cat extends Animal {
void makeSound() {
System.out.println("고양이가 야옹하고 웁니다.");
}
}
public class Practice {
public static void main(String[] args) {
Cat cat = new Cat();
// new Cat() : Cat 타입으로 cat 변수 선언
cat.makeSound();
// 출력 >> "고양이가 야옹하고 웁니다."
}
}