在类 Parent 的以下程序中,类 Child 实现了 MyInterface。这就是为什么 MyInterface 的 obj1(父)实例是假的,而 MyInterace 的 obj2(子)实例是真的吗?
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
因为只有你的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
就现实世界的对象而言,它非常简单。将以下示例与给定的 java 对象映射。我有以下类和接口:
class HumanBeing{}
interface Teachable{}
class Teacher extends HumanBeing implements Teachable{}
真实世界的例子:
上面的类和接口定义可以解释如下:
- "人"存在于世界上
- 所有的"老师"都是"可教"的人
這意味著要成為一位老師,必須是一個人。现在说,例如戈帕尔只是"人类",而瓦尔玛是"老师"
HumanBeing gopal = new HumanBeing();
HumanBeing varma = new Teacher();
现在评估以下问题,您将轻松理解概念:
- 戈帕尔是人类吗?是的
- 戈帕尔可以教吗?不
戈帕尔是老师吗?不
瓦尔玛是人类吗?是的,因为他是老师(所有的老师都是人)
- 瓦尔玛可教吗?是的
- 瓦尔玛是老师吗?是的