Animal a = new Dog(); // 업캐스팅 (자동 형변환)
Dog d = (Dog) a; // 다운캐스팅 (강제 형변환)
a
가Dog
타입 이면 가능
아니면ClassCastException
발생
자세한 내용은 아래에 있습니다
package chap07;
public abstract class HttpServlet {
public abstract void service();
}
package chap07;
public class LoginServlet extends HttpServlet {
@Override
public void service() {
System.out.println("로그인 합니다");
}
}
package chap07;
public class FileDownloadServlet extends HttpServlet{
@Override
public void service() {
System.out.println("파일 다운로드합니다.");
}
}
package chap07;
public class HttpServletEx {
public static void main(String[] args) {
method(new LoginServlet());
method(new FileDownloadServlet());
}
public static void method(HttpServlet servlet){
servlet.service();
}
}
HttpServlet
은 추상 클래스이며 그 안에service()
라는 추상 메서드를 정의
따라서 자식 클래스에서service()
을 구현해야함
자식 클래스
Login
,FileDownload
는HttpServlet
의 자식이기 때문에HttpServlet
타입으로도 받기 가능HttpServlet servlet = new LoginServlet(); HttpServlet servlet = new FileDownloadServlet(); 과 같은 말이다
따라서 메서드 내부에서
servlet.service()
를 호출하면 오버라이딩된LoginServlet
과FileDownloadServlet
안의 service 메서드가 호출된다
package chap07;
public class CellPhone {
//필드
String model;
String color;
//생성자
/* public CellPhone() {
//System.out.println("CellPhone() 호출됨");
}
자식 클래스에서 super() 부모 호출 한 곳
*/
//메소드
void powerOn() {System.out.println("전원을 켭니다.");}
void powerOff() {System.out.println("전원을 끕니다.");}
void bell() {System.out.println("벨이 울립니다.");}
void sendVoice(String message) {System.out.println("자기: " + message);}
void receiveVoice(String message) {System.out.println("상대방: " + message);}
void hangUp() {System.out.println("전화를 끊습니다.");}
}
package chap07;
public class DmbCellPhone extends CellPhone {
// 필드
int channel;
// 생성자
DmbCellPhone(String model, String color, int channel) {
//super(); -> 부모 클래스 호출
this.model = model;
this.color = color;
this.channel = channel;
}
// 메소드
void turnOnDmb() {
System.out.println("채널 " + channel + "번 DMB 방송 수신을 시작합니다.");
}
void changeChannelDmb(int channel) {
this.channel = channel;
System.out.println("채널 " + channel + "번으로 바꿉니다.");
}
void turnOffDmb() {
System.out.println("DMB 방송 수신을 멈춥니다.");
}
}
package chap07;
public class DmbCellPhoneExample {
public static void main(String[] args) {
//DmbCellPhone 객체 생성
DmbCellPhone dmbCellPhone = new DmbCellPhone("자바폰", "검정", 10);
//CellPhone 클래스로부터 상속 받은 필드
System.out.println("모델: " + dmbCellPhone.model);
System.out.println("색상: " + dmbCellPhone.color);
//DmbCellPhone 클래스의 필드
System.out.println("색상: " + dmbCellPhone.channel);
//CellPhone 클래스로부터 상속받은 메소드 호출
dmbCellPhone.powerOn();
dmbCellPhone.powerOff();
dmbCellPhone.sendVoice("여보세오.");
dmbCellPhone.receiveVoice("안녕하세요! 저는 홍길동인데요");
dmbCellPhone.sendVoice("아~ 예 반갑습니다.");
dmbCellPhone.hangUp();
//DmbCellPhone 클래스의 메소드 호출
dmbCellPhone.turnOnDmb();
dmbCellPhone.changeChannelDmb(12);
dmbCellPhone.turnOffDmb();
}
}
package chap07;
public class Calculator {
double areaCircle(double r) {
System.out.println("Calculator 객체의 areaCircle() 실행");
return 3.14159 * r * r;
}
}
package chap07;
public class Computer extends Calculator {
@Override
double areaCircle(double r) {
System.out.println("Computer 객체의 areaCircle() 실행");
return Math.PI * r * r;
}
}
package chap07;
public class ComputerEx {
public static void main(String[] args) {
int r = 10;
Calculator calculator = new Calculator();
System.out.println("원면적: " + calculator.areaCircle(r));
System.out.println();
Computer computer = new Computer();
System.out.println("원면적: " + computer.areaCircle(r));
}
}
→ 내려올 수록 접근 제한이 강화
Animal animal = new Cat();
객체 A는 객체 B, C, D, E를 상속 받고 있다
객체 D는 객체 A, B타입을 자동 변환이 가능
객체 E는 객체 A, C타입을 자동 변환이 가능
❌ 객체 D는 C타입으로 변환 불가
❌ 객체 E는 B타입으로 변환 불가
package chap07;
class A {}
class B extends A {}
class C extends A {}
class D extends B {}
class E extends C {}
public class AutoTypeEx {
public static void main(String[] args) {
B b = new B();
C c = new C();
D d = new D();
E e = new E();
A a1 = b;
A a2 = c;
A a3 = d;
A a4 = e;
B b1 = d;
C c1 = e;
//불가능
//B b3 = e;
//C C2 = d;
}
}
A a = new B();
B b = (B) a;
C c = (C) a; //사용 불가능
package chap07;
public class Parent {
public String field1;
public void method1() {
System.out.println("Parent-method1()");
}
public void method2() {
System.out.println("Parent-method2()");
}
}
package chap07;
public class child extends Parent{
public String field2;
public void method3() {
System.out.println("Child-method3()");
}
}
package chap07;
public class ChildEx {
public static void main(String[] args) {
Parent parent = new child(); //자동 타입 변환
parent.field1 = "data1";
parent.method1();
parent.method2();
//불가능
//parent.field2 = "data2";
//parent.method3();
child child = (child) parent; //강제 타입 변환
child.field2 = "data2";
child.method3();
}
}