【问题标题】:Clarification on the hierarchy of the command Interface澄清命令接口的层次结构
【发布时间】:2014-11-21 10:22:46
【问题描述】:

在 Parent 类的以下程序中,Child 类实现 MyInterface。这就是 obj1 (Parent) instanceof MyInterface 为 false,而 obj2 (Child) instanceof MyInterace 为 true 的原因吗?

    class InstanceofDemo {
    public static void main(String[] args) {

        Parent obj1 = new Parent();
        Parent obj2 = new Child();

        System.out.println("obj1 instanceof Parent: "
            + (obj1 instanceof Parent));
        System.out.println("obj1 instanceof Child: "
            + (obj1 instanceof Child));
        System.out.println("obj1 instanceof MyInterface: "
            + (obj1 instanceof MyInterface));
        System.out.println("obj2 instanceof Parent: "
            + (obj2 instanceof Parent));
        System.out.println("obj2 instanceof Child: "
            + (obj2 instanceof Child));
        System.out.println("obj2 instanceof MyInterface: "
            + (obj2 instanceof MyInterface));
    }


}

class Parent {}
class Child extends Parent implements MyInterface {}
interface MyInterface {}

给出以下输出:

obj1 instanceof Parent: true
obj1 instanceof Child: false
obj1 instanceof MyInterface: false
obj2 instanceof Parent: true
obj2 instanceof Child: true
obj2 instanceof MyInterface: true

【问题讨论】:

  • 是的,这就是原因。如果 Parent 没有实现 MyInterface,instanceof 语句将返回 false。

标签: java


【解决方案1】:

因为只有你的Child 类实现MyInterface,所以如果你想要一个Parent 类的实例是你的MyInterface 接口的一个实例,你必须在你的Parent 类中实现MyInterface .像这样:

class Parent implements MyInterface{}
class Child extends Parent {}
interface MyInterface {}

这将给出以下输出:

obj1 instanceof Parent: true
obj1 instanceof Child: false
obj1 instanceof MyInterface: true
obj2 instanceof Parent: true
obj2 instanceof Child: true
obj2 instanceof MyInterface: true

【讨论】:

    【解决方案2】:

    就现实世界的对象而言,它非常简单。使用给定的 java 对象映射下面的示例。 我有以下类和接口:

    class HumanBeing{}
    interface Teachable{}
    class Teacher extends HumanBeing implements Teachable{}
    

    真实世界示例:

    上面的类和接口定义可以解释如下:

    • “人”存在于世间
    • 所有“老师”都是“可教”的人

    这意味着成为一名教师必须是一个人类。 现在说例如 Gopal 只是“人类”而 Varma 是“老师”

    HumanBeing gopal = new HumanBeing();
    HumanBeing varma = new Teacher();
    

    现在评估以下问题,您将很容易理解这个概念:

    • Gopal 是人类吗?是的
    • Gopal 可教吗?没有
    • 是Gopal老师吗?没有

    • Varma 是人类吗?是的,因为他是老师(所有老师都是人)

    • Varma 是可教的吗?是的
    • 是瓦玛老师吗?是的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-21
      • 2019-10-22
      • 2014-04-10
      • 1970-01-01
      • 2014-12-07
      • 2022-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多