JAVA
Object type casting(upcasting,downcasting) example in Java
seoca
2019. 6. 17. 08:06
Upcasting을 이용하면 부모객체로 부터 상속받은 메서드를 사용할 수 있게된다. 즉, 단 하나의 부모클래스의 객체(PhoneInfo)로 여러가지 자식 메서드(univPhoneInfo, companyPhoneInfo, friendPhoneInfo)를 검색할 수 있는 장점이 있다.
Example I
public class PhoneInfo {
String name;
String phoneNum;
public PhoneInfo(String name, String num){
this.name = name;
phoneNum = num;
}
public void showInfo(){
System.out.println("name: " + name);
System.out.println("phone: " + phoneNum);
}
}
public class PhoneUnivInfo extends PhoneInfo{
String major;
int year;
public PhoneUnivInfo(String name, String num, String major, int year){
super(name,num);
this.major = major;
this.year = year;
}
public void showInfo(){
super.showInfo();
System.out.println("major: " + major);
System.out.println("year: " + year);
}
}
public class PhoneManager {
final int MAX = 100;
int curCnt;
PhoneInfo[] phoneInfo = new PhoneInfo[MAX];
//Upcasting
//return parent class type
public PhoneInfo univInput(){
System.out.print("name: ");
String name = MenuViewer.keyboard.nextLine();
System.out.print("phone: ");
String phone = MenuViewer.keyboard.nextLine();
System.out.print("major: ");
String major = MenuViewer.keyboard.nextLine();
System.out.print("year: ");
String year = MenuViewer.keyboard.nextLine();
MenuViewer.keyboard.nextLine();
//return child class
return new PhoneUnivInfo(name,phone,major,year);
}
}
|
Example II
class Animal{
void walk(){
System.out.print("I am walking. from Animal ");
}
void talk(){
System.out.println("Am I ?");
}
}
class Bird extends Animal{
void walk(){
super.walk();
System.out.println("I am walking. from Bird");
}
void sing(){
System.out.println("I am singing");
}
}
public class Main{
public static void main(String args[]){
Animal[] animal = new Animal[10];
Bird bird = new Bird();
bird.walk(); //I am walking. from Animal I am walking. from Bird
bird.talk(); //Am I? // 상속: 하위클래스가 상위클래스의 메서드 그대로 사용가능.
animal[2] = new Bird(); //Upcasting: Implicitly 부모타입으로 자식객체를 참조할 수 있다. 이럴 경우 상위클래스에서 상속받은 메서드만 사용가능
animal[2].walk(); //I am walking. from Animal I am walking. from Bird
((Bird)animal[2]).sing(); //I'm singing //Downcasting: Explicitly 하위클래스 사용하려면 클래스형변환을 사용하여 접근이 가능하다.
}
}
|
Reference