
class Parent {
void yj() {
System.out.println("Hello from Parent!");
}
}
class Child extends Parent {
void yjChild() {
System.out.println("Hello from Child!");
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.yj(); // 부모 클래스의 메서드
child.yjChild(); // 자식 클래스의 메서드
}
}
Hello from Parent!
Hello from Child!
그렇다면, 밑의 코드는 과연 가능할까?
public class Main {
public static void main(String[] args) {
사람 a사람 = new 심슨();
}
}
정답은 불가능이다. 사람의 리모콘 a사람은 사람만 인식 할 수 있다.
그런데, 이를 가능하게 할 수 있다.
public class Main {
public static void main(String[] args) {
사람 a사람 = new 사람();
a사람 = new 심슨();
}
}
class 사람 { }
class 심슨 extends 사람 { }
위의 코드처럼 a사람(리모콘)은 원래는 사람만 사용 할 수 있지만, class를 통해 심슨 extends(도) 사실은 사람이다라고 java에게 알려주면 a사람(리모콘)은 심슨이 될 수 있다.
abstract는 Java에서 추상 클래스와 추상 메서드를 정의하는 데 사용됩니다. 추상 클래스와 메서드는 객체 지향 프로그래밍(OOP)에서 "설계의 틀"을 제공하며, 하위 클래스에서 구현 세부 사항을 제공해야 합니다.
abstract class Animal {
abstract void makeSound(); // 추상 메서드 (구현 없음)
void eat() { // 일반 메서드 (구현 있음)
System.out.println("This animal eats food.");
}
}
abstract class Animal {
abstract void makeSound(); // 하위 클래스에서 구현해야 함
}
// 추상 클래스
abstract class Animal {
// 추상 메서드
abstract void makeSound();
// 일반 메서드
void eat() {
System.out.println("This animal eats food.");
}
}
// 하위 클래스
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Woof! Woof!");
}
}
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Meow! Meow!");
}
}
public class Main {
public static void main(String[] args) {
Animal dog = new Dog();
dog.makeSound(); // Woof! Woof!
dog.eat(); // This animal eats food.
Animal cat = new Cat();
cat.makeSound(); // Meow! Meow!
cat.eat(); // This animal eats food.
}
}
Woof! Woof!
This animal eats food.
Meow! Meow!
This animal eats food.