[java] 상속을 통한 클래스별 특성 구현
자바에서는 상속(inheritance)을 통해 부모 클래스의 특성을 자식 클래스에게 물려줄 수 있습니다. 이를 통해 코드 재사용성과 유지보수가 용이해지며, 객체 지향 프로그래밍의 근간을 이루는 중요한 기능입니다.
부모 클래스 선언
public class Animal {
protected String species;
protected int age;
public Animal(String species, int age) {
this.species = species;
this.age = age;
}
public void eat() {
System.out.println("The " + species + " is eating.");
}
// 기타 메서드 및 특성
}
위의 코드에서 Animal
클래스를 정의하였으며, 종(species)과 나이(age)를 나타내는 필드와 eat
메서드를 포함하고 있습니다.
자식 클래스 정의
public class Dog extends Animal {
private String breed;
public Dog(String species, int age, String breed) {
super(species, age);
this.breed = breed;
}
public void bark() {
System.out.println("The " + breed + " dog is barking.");
}
// 기타 메서드 및 특성
}
위의 코드에서 Dog
클래스는 Animal
클래스를 상속받아 구현되었습니다. breed
필드와 bark
메서드를 추가로 정의하였습니다.
객체 생성 및 활용
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog("Canis lupus familiaris", 3, "Labrador Retriever");
myDog.eat(); // Animal 클래스의 메서드
myDog.bark(); // Dog 클래스의 메서드
}
}
위의 Main
클래스에서 Dog
클래스를 이용한 객체를 생성하고, 부모 클래스인 Animal
클래스의 eat
메서드와 자식 클래스 Dog
의 bark
메서드를 호출하는 예시를 보여주고 있습니다.
자바에서 상속을 이용하면 클래스 간에 코드를 재사용하고 중복을 피함으로써 효율적인 프로그래밍을 할 수 있습니다.
참고 자료
- Oracle Java Documentation: Inheritance in Java