Interface Polymorphism

  • Polymorphism(다형성)

Tv t = new SmartTv();

Parent reference type variable indicates child object. Likewise, interface as well.

  • Paremeter type is interface

: The parameter is ONLY implemented class!

  • Return type is interface

: Return type can be interface itself and the class that implements its interface.

Why return type is interface?

Because of Abstration, if the class implements interface, it can be return type. Here the Fighter implments Fightable(interface), that can be any other class if it implements Fightable(interface)

abstract class Unit {
    int x,y;
    abstract void move(int x, int y);
    void stop() {System.out.println("멈춥니다");
}

interface Fightable {
    public abstract void move(int x, int y);
    public abstract void attack(Fightable f);//parameter type is interface!
    //f is implemented class!
}

class Fighter extends Unit imiplements Fightable {
    public void move(int x, int y) {
        System.out.println("["+x+","+y+"]로 이동합니다");
    }
    public void attack(Fightable f) {
        System.out.println(f+"를 공격합니다");
    }
    //return type of method getFightable is interface Fightable.
    Fightable getFightable() {
        //return Fighter
        //because of interface polymorphism, it is possible.
        return new Fighter();
        //Fighter = new Fighter();
        //return Fighter;
    }
}

//main
public class FighterTest {
    public static void main(String[] args) {
        Fighter FFF = new Fighter();
        Fightable f2 = FFF.getFightable();
        //match variable type = return type of method
        //return type of FFF.getFightable() is Fightable
        //so put it the Fightable type.
        
        System.out.println("Fighter");
        Fighter f = new Fighter();
        f.move(100,200);
        //parameter type is interface
        //parameter Fighter implemented Fightable
        f.attack(new Fighter());
        
        System.out.println("Unit");
        //Unit is parent class of . Fighter
        Unit u = new Fighter();
        u.move(100,200);
        u.stop();
        //error. bc Unit does not have attack method
        //u.attack(new Fighter());
        
        System.out.println("Fightable");
        //Unit is parent class of . Fighter
        Fightable f4 = new Fighter();
        f4.move(100,200);
        f4.attack(f4);
        
        
    }
}

Last updated