본문 바로가기

프로그래밍 언어/Java

Week6) Java Programming Lab : Polymorphism

Java-Lecture6.pdf
0.73MB


1. What is Polymorphism?

  • 다형성
  • program in general -> 프로그램 사용자가 구체적인 부분 변형 
  • upcasting : dog2 = new PoliceDog(); 
  • 부모 클래스 객체가 자식 클래스를 참조하는 것 
public class Dog {
	private String type;
    private int age;
    
    // object class (최상위) override 
    public String toString(){
    	return "Dog class";
    }
}

class PetDog extends Dog {
	private String owner;
    private String FoodType;
    
    public String toString(){
    	return "PetDog class";
    }
}

class PoliceDog extends PetDog{
	private String PolicID;
    
    public String toString(){
    	return "PoliceDog class";
    }
}

class Testing {
	public static void main(String[] args){
    	Dog dog1 = new Dog();
        Dog dog2, dog3, dog4;
        
        // general class에서 instance -> polymorphism 
        dog2 = new PoliceDog();
        dog3 = new PetDog();
        dog4 = dog3; 
        
        System.out.println(dog2.toString());
        // PoliceDog class
    }
}

 

2. Downcasting

  • dog3 = new Dog():
  • 자식 클래스의 인스턴스가 부모 클래스로 다시 참조하는 것  
  • 권장되지 않음 
public class Parent()
public class Child extends Parent(){
	public static void main(String args[]) {
    	Parent parent = new Child();
        Child child = (Child) Parent();
        // valid downcasting 
    }
}
...
PoliceDog dog5;

dog5 = new Dog(); 
// downcasting -> error 

dog5 = (PoliceDog) new Dog();
// runtime error 

Dog dog5 = new PoliceDog();
PoliceDog dog6 = (PoliceDog) dog5;
// no error dog5는 Dog 객체이지만 PoliceDog를 참조하고 있기 때문에 downcasting 가능

3. Polymorphism using Abstract Classes

  • public abstract class Employee{}
  • public abstract void draw();
  • abstract superclass : 실제 객체를 만들기에 너무 general 한 것, subclass 간 공통적인 것만을 명시함 
  • abstract 메소드는 구현을 제공하지 않음 (virtual method) 
  • abstract메소드는 반드시 abstract class 안에만 존재 
  • abstract class - 오브젝트 만들 수 없음 

5. Polymorphism using Interface

  •  

References

  • 성균관대학교 소프트웨어학과 타메르 교수님 2021-1 <자바 프로그래밍 실습>