KeyWords : 상속, Casting, 다형성
super: 부모의 주소값(참조값)
super() : 부모 생성자
: 매개변수가 다른 동일한 이름의 메소드를 중복해서 정의하는 것
: 부모클래스에서 선언한 메소드를 자식 클래스에서 수종하고자 부모클래스에서 선언한 메소드의 이름, 매개변수의 형태와 동일하게 선언, 즉 재정의하는 것
// class Bike ===============================================
package casting;
public class Bike {
// fields
int wheel;
int price;
String color;
String brand;
// constructor.
// tab source -> generate constructor using fields
public Bike() {
super();
}
public Bike(int wheel, int price, String color, String brand) {
super();
this.wheel = wheel;
this.price = price;
this.color = color;
this.brand = brand;
}
// method
void move() {
System.out.println("Operation Started");
}
void stop() {
System.out.println("Operation Stopped");
}
}
// class ElectricBike ===============================================
package casting;
public class ElectricBike extends Bike {
// [ fields ]
int power;
int maxCharge;
int currentCharge;
// [ constructor ]
public ElectricBike() {
super();
}
public ElectricBike(int power, int maxCharge, int currentCharge) {
super();
this.power = power;
this.maxCharge = maxCharge;
this.currentCharge = currentCharge;
}
// method
void getCharge() {
System.out.println("Charging in process");
}
void getSpeedUp() {
System.out.println("Speeding up charging");
}
// [ method overriding ]
// tab source -> Override / Implement Methods
@Override
void move() {
System.out.println("Electric Bike Operation Started");
// ** Bike 클래스의 move() 메소드가 호출됨
super.move(); // 기존에 있는 메소드 내용에 더 추가하겠다는 것
}
@Override
void stop() {
System.out.println("전기 자전거를 멈춥니다");
}
// 직접 타이핑한 코드
// @Override // annotation (컴파일러에게 알려주는 주석이라 없어도 있어도 괜찮지만 오버라이딩이라는걸 알려주는것)
// void move() { // annotation 해주면 매개변수를 새로 만들었을때 새로운 메소드 취급을 받아서 오류라고 뜸
// System.out.println("Electric Bike Operation Started");
// }
}
// class Cast ===============================================
package casting;
public class Cast {
public static void main(String[] args) {
ElectricBike eBike = new ElectricBike();
System.out.println(eBike.brand); // null
eBike.move(); // 재정의한 메소드와 super class 메소드가 출력
eBike.stop(); // 자식클래스에서 재정의한 메소드로 정상 실행
}
}
객체의 타입 비교 (instance of)
a instance of A : a 객체가 클래스 A 타입이면 true, 아니라면 false
// class Cast ================================================
// instanceof : a instance of A
System.out.println(eBike instanceof ElectricBike);
System.out.println(eBike instanceof Bike);
System.out.println(eBike instanceof Object);
// 부모클래스는 자식클래스의 타입, 멤버를 가지지 않음
// bike 객체는 Bike, Object 클래스 타입을 가짐
Bike bike = new Bike();
System.out.println(bike instanceof Bike);
System.out.println(bike instanceof ElectricBike); // false
System.out.println(bike instanceof Object);
// class Cast ======================================================
// up casting : 자식객체 -> 부모 타입으로 형변환 (자동, 암묵적)
Bike newBike = new ElectricBike();
// down casting : {부모 객체 -> 자식타입으로 형변환}이 아닌 {up casting 된 자식객체를 자식타입으로 형변환}
// ElectricBike newElectric = (ElectricBike) new Bike();
// Bike가 갖고있는 클래스가 아니라 형변환 불가능
// 이런식으로 앞에 (double) 처럼 (electricBike) 명시해줘야함
//int num = 10;
//System.out.println({double)num);
// 부모 객체를 자식타입으로 형변환 할 수 없음 (실행시 오류발생)
// *** down casting은 up casting 된 객체를 다시 원상복귀 시킬 때 사용 ***
ElectricBike newElectric2 = (ElectricBike) newBike;
up casting : 다양한 타입을 한번에 관리하기 위해
down cadsting : up casting 된 자식에서 자식 클래스의 멤버를 사용하기 위해
모든 자식 객체를 하나의 저장공간으로 전달받는 것은 자식끼리는 서로 타입이 다르기 때문에 불가능
그래서 up casting을 사용하여 모든 자식 객체를 부모타입의 저장공간(변수에) 한번 전달 받아서 사용
단 상속받은 메소드를 자식 클래스에서 오버라이딩(재정의) 해두었다면 up casting 된 상태로도 사용 가능
: 하나의 객체가 여러가지 형태(타입을 가지는 것)
: 필드, 메소드, 클래스의 접근 권한을 제어하는 것
보안의 강도, 범위에 따라 달라짐
[접근 제한자] [키워드] [자료형] [변수명]
: 필드 사용시
[접근 제한자] [키워드] [리턴타입...]
: 메소드 사용시
getter : get + 필드명
필드의 값을 가져올 때 사용
setter : set + 필드명
필드의 값을 수정/저장 할 때 사용