
public class 자식클래스 extends 부모클래스{
}
public class SmartPhone extends Phone{
}
//this.을 활용해 부모 클래스 필드와 메소드를 쓰면 된다
super(); 에 의해 호출된다 (직접 안 써도 자동으로 생성됨)super(매개값, …); 을 넣어줘야 한다public class Smart extends Phone{
// 자식 생성자 선언
public Smart(String model, String color){
super(model, color);
}
}
@override를 붙이면 컴파일 단계에서 오버라이딩 체크를 해준다@override
public void fly(){
if(flyMode == SUPERSONIC){
}
else{
super.fly();
}
}
public final class 클래스명{}
public final 리턴타입 메소드(매개변수, ...){}
// 부모타입 변수 = 자식타입 객체;
Cat cat = new Cat();
Animal animal = cat;
→ cat과 animal 변수는 타입만 다르지 동일한 Cat 객체를 참조한다
// 자식타입 변수 = (자식타입) 부모타입객체;
Parent parent = new Child(); // 자동 타입 변환
Child child = (Child) parent; // 강제 타입 변환
// Car 객체 생성
Car myCar = new Car();
// HankookTire 장착
myCar.tire = new HankookTire();
// KumhoTire 장착
myCar.tire = new KumhoTire();
→ 어떤 타이어를 장착했느냐에 따라 결과가 달라진다
public class Driver{
public void drive(Vehicle vehicle){ //클래스 타입의 매개변수
vehicle.run();
}
}
//main
Driver driver = new Driver();
Bus bus = new Bus();
driver.drive(bus);
Taxi taxi = new Taxi();
driver.drive(taxi);
public void method(Parent parent){
if(parent instanceof Child){
Child child = (Child) parent;
}
}
public abstract class 클래스명{
// 필드
// 생성자
// 메소드
}
//extends를 이용해 추상 클래스 상속받기
// abstract 리턴타입 메소드명(매개변수, ...);
public abstract class Animal{
abstract void sound();
}
// Person의 자식 클래스는 Employee, Manager만 가능
public sealed class Person permits Employee, Manager{...}
// final : 더이상 상속 불가능
public final class Employee extends Person{...}
// non-sealed : 봉인 해제
// Manage를 부모 클래스로 하는 자식 클래스 생성 가능
public non-sealed class Manager extends Person{...}
이것이 자바다(신용권, 임경균 지음)