在java中将接口转换为upperclass

时间:2015-10-24 09:13:58

标签: java interface casting

所以我定义了一个接口

public interface Behavior {
public void eat();

public void sleep();}

我定义了一个这样的类

class Son extends Father implements Behavior {

@Override
public void eat() {
    System.out.println("eat");
}

@Override
public void sleep() {
    System.out.println("sleep");
}
}

创建变量Father father = new Son()

之后是否有意义

使用类似(行为)父的转换,如果有,它是如何工作的?它会从对象Son调用方法吗?

2 个答案:

答案 0 :(得分:0)

由于动态方法绑定/多态,在运行时JVM将始终使用对象类型而不是引用类型。所以它仍然会调用对象Son的方法。

答案 1 :(得分:0)

可视化将对象投射为在该对象上放置新衣服。它有不同的外观,但在你穿上它的任何衣服下面,它仍然是同一个物体。

以下代码段将清除您的疑虑

   class Father
{
    public void getFather()
    {
        System.out.println("inside father ");
    }
}

interface Behavior {
    public void eat();

    public void sleep();

}
class Son extends Father implements Behavior 
{

    public void eat() {
        System.out.println("Son Eat");

    }

    public void sleep() {
        System.out.println("Son slepp");

    }

    public void getSon()
    {
        System.out.println("in son class");
    }

}

public class A 
{
    public static void main(String [] args)
    {
        Father f=new Son();
        f.getClass() ; //only method available 
        Behavior beh=(Behavior)f;
        beh.sleep();// methods declared in Behavior interface
        beh.eat();// methods declared in Behavior interface
        Son s =(Son)f;
        s.getSon();//methods declared in Behavior as well as methods defined in Son are available
    }
}

另见: What class does the target object take on after casting?

特别是Bill K回答