【问题标题】:casting interface to upperclass in java将接口转换为java中的上层
【发布时间】:2016-01-23 19:47:26
【问题描述】:

所以我定义了一个接口

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()后是否有意义,

使用像 (Behavior)father 这样的转换,如果是,它是如何工作的?它会从对象 Son 调用方法吗?

【问题讨论】:

    标签: java interface casting


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      将投射一个对象想象为在该对象上穿上新衣服。它有不同的外观,但无论你穿什么衣服,它仍然是同一个物体。

      跟着sn-p就能解开你的疑惑

         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?

      特别是比尔 K 的回答

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-02
        • 1970-01-01
        相关资源
        最近更新 更多