2014-11-21 38 views
0

在類中的以下程序中父類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 
+0

是的,這是原因。如果Parent沒有實現MyInterface,則instanceof語句將返回false。 – 2014-11-21 10:25:37

回答

0

,因爲只是你Child類實現MyInterface,所以如果你想你的Parent類的實例是你的你MyInterface接口的情況下,你必須實現MyInterface在你的Parent類中。事情是這樣的:

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 
0

它是在現實世界中的物體而言是非常簡單的。將下面的示例映射到給定的java對象。 我有下面的類和接口:

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

真實的例子:

上面的類和接口定義可以這樣解釋如下:

  • 「人」存在世界
  • 所有「老師」都是「可教」的人類

這意味着成爲一名教師必須是一個人。 現在比方說戈帕爾只是「人」和瓦瑪是「老師」

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

現在評估下面的問題,你會很容易理解的概念:

  • 是戈帕爾人?是
  • 是Gopal可教? NO
  • 是Gopal老師? NO

  • 是否是Varma人類?是的,因爲他是老師(所有老師都是人類)

  • 是Varma可教?是
  • 是Varma老師?是的