자바는 Python 과 달리 그렇게 친절한 코드는 아닙니다. 물론, 이 친절함의 비중은 입장에 따라 달라지겠지만. Python 이 사용자에게 친절한 것이라면 Java 나 C# 계열의 언어들은 컴퓨터에게 친절한 언어가 되겠습니다. 말이 컴퓨터지, 사실상 코드를 배우다 보면 혼자서 알아서 할 줄 아는게 없는 친구니까요.
오늘은 Java의 상속과 Override 를 내 스스로에게 설명해보는 과정입니다
우리의 소중한 친구, W3에서 코드를 가져와서 봅시다.
class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}
}
class Car extends Vehicle {
private String modelName = "Mustang"; // Car attribute
public static void main(String[] args) {
// Create a myCar object
Car myCar = new Car();
// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class
System.out.println(myCar.brand + " " + myCar.modelName);
}
}
이 코드은 Vehicle 이라는 차량(탈 것) 이라는 것에서, Car(자동차)을 주고있습니다.
논리적으로 생각을 해보면,
자동차도 탈 것의 하나니까.
그 넓은 개념을 상속받는 것에 문제는 없어보입니다.
비슷한 예시를 들어봅시다
Phone 은 SmartPhone 을
Printer 는 3DPrinter 을
이렇게 다음세대를 가져올 수도 있고
Animal 은 Dog를 가져올 수도 있을 것입니다
대충 감이 잡히시나요?
이 Inherit 이라는 단어가 의미하는 것처럼
(컴퓨터쪽에서는 상속이라고 번역함 - 유전이라는 뜻도 있음)
본래의 코드가 의미하는 성질을 다음세대에 재활용 할 수 있게 해주는 마법같은 녀석입니다.
그렇다면 코드의 재활용과 유지보수가 어렵지 않겠죠?
이 녀석의 포괄적인 개념은 여기까지하고, 이제 활용에 들어가는 것을 공부해 봅시다.
Animal(동물) 이라는 코드를 Dog(개)가 상속하고 있습니다
class Animal {
void makeSound() {
System.out.println("Some generic animal sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Woof! Woof!");
}
void wagTail() {
System.out.println("Dog is wagging its tail.");
}
}
public class Main {
public static void main(String[] args) {
Animal genericAnimal = new Animal();
Dog myDog = new Dog();
// Calling the makeSound method of the Animal class
genericAnimal.makeSound();
// Calling the overridden makeSound method of the Dog class
myDog.makeSound();
// Calling the wagTail method specific to the Dog class
myDog.wagTail();
}
}
어? 보니까 이상한 녀석이 있네요. 듣도 보지도 못한 @Override 라는 녀석이 있습니다.
이 친구는 어떤 친구일까요?
직역을 하면, 덮어 씌우다. 라는 말을 지니고 있습니다.
즉, 본래 Animal 안에 있는 메소드를 자식 클래스에서 다르게 쓰였을때.
컴퓨터에게 "이 코드는 다시, 다르게 쓰인 녀석이야" 알려주는 표식입니다.
이 Override는 Super()와 함꼐 자주 쓰이니까 기억해두세요!
Super()는 다음 포스팅에서 공부해보겠습니다.