Java 关于命令界面层次结构的澄清
在类父级中的以下程序中,类子级实现MyInterface。这就是为什么MyInterface的obj1父实例为false,而MyInterace的obj2子实例为true的原因吗Java 关于命令界面层次结构的澄清,java,Java,在类父级中的以下程序中,类子级实现MyInterface。这就是为什么MyInterface的obj1父实例为false,而MyInterace的obj2子实例为true的原因吗 class InstanceofDemo { public static void main(String[] args) { Parent obj1 = new Parent(); Parent obj2 = new Child(); System.
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
因为只有您的子类实现MyInterface,所以如果您希望父类的实例成为MyInterface接口的实例,则必须在父类中实现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
就现实世界的对象而言,它非常简单。将下面的示例映射到给定的java对象。 我有以下类和接口:
class HumanBeing{}
interface Teachable{}
class Teacher extends HumanBeing implements Teachable{}
现实世界的例子:
上述类和接口定义可解释如下:
人存在于世界之中
所有的老师都是可教的人
这意味着要成为一名教师,必须是一个人。
比如说,戈帕尔只是人类,而瓦玛是老师
HumanBeing gopal = new HumanBeing();
HumanBeing varma = new Teacher();
现在评估以下问题,您将很容易理解该概念:
戈帕尔是人吗?对
戈帕尔可以教吗?不
戈帕尔是老师吗?没有
瓦玛是人类吗?是的,因为他是老师,所有的老师都是人
瓦尔玛可以教吗?对
瓦玛是老师吗?对
是的,这就是原因。如果父级未实现MyInterface,instanceof语句将返回false。