class Shape {
public void answer() {
System.out.println("Shape answer");
}
}
class Circle extends Shape {
@Override
public void answer() {
System.out.println("Circle answer");
}
public void question() {
System.out.println("Circle question");
}
}
🟢 Shape shape = new Circle() 객체 생성 후, shape.question(); 입력시 오류 발생 (Shape 클래스에서 없는 함수이기 때문임)
class Cake {
public void yummy() {
System.out.println("Yummy Cake");
}
}
class CheeseCake extends Cake {
public void yummy() {
System.out.println("Yummy Cheese Cake");
}
}
public class java_13_p8 {
public static void main(String[] args) {
Cake c1 = new CheeseCake();
CheeseCake c2 = new CheeseCake();
c1.yummy();
c2.yummy();
}
}
🟢 Yummy Cheese Cake 2번 출력
(오버라이딩된 자식의 함수가 호출됨)
🟢 다형성이 적용되고 오버라이딩이 적용되었을 때, 상위클래스의 함수를 가져오고 싶다면 super 이용
다형성을 이용하여 부모 = 자식으로 업케스팅
Shape circleShape = new Circle(10);
Circle circle = (Circle) circleShape;
System.out.println(circle.getArea());
🟢 2가지 조건
1. 미리 자식으로 메모리에 올라가 있어야 함
2. (Circle)과 같이 형변환이 없으면 에러 발생
함수의 매개변수에 상위 클래스를 설정하면, 하위 클래스를 매개변수로 받을 수 있음
변수명 instanceof 데이터타입으로 사용int, byte, short, long, float, double, boolean, char추상 클래스 : 하나 이상의 추상 메소드를 포함하는 클래스
추상 메소드 : 자식 클래스에서 반드시 오버라이딩해야만 사용할 수 있는 메소드 (미완성 메소드)
🟢 클래스와 메소드 앞에 abstract를 붙임
일반 메소드로 정의되면 자식 클래스에서 오버라이딩하지 않아도 컴파일러가 체크할 방법이 없음
객체를 어떻게 구성해야 하는지 정리한 설계도
class 대신 interface를 작성인터페이스의 일반함수(구현된 함수)
interface Driable {
void drive();
}
interface Flyable {
void fly();
}
class FlyingCar implements Driable, Flyable{
@Override
public void fly() {
System.out.println("날 수 있습니다.");
}
@Override
public void drive() {
System.out.println("드라이브가 가능합니다.");
}
}
public class java_14_p12 {
public static void main(String[] args) {
FlyingCar flyingCar = new FlyingCar();
flyingCar.drive();
flyingCar.fly();
}
}
🟢 class FlyingCar implements Driable, Flyable 로 Driable과 Flyable 인터페이스를 동시에 상속