2015-09-13 43 views
-3

我剛開始使用Java,遇到了這個問題。我不確定我的輸出是否正確。我還希望在這種情況下使用'getClass()'方法的更多細節,因爲'Orc'和'Unicorn'不會從同一個類繼承。我想檢查我的輸出是否正確。而且,這個'getClass()'方法的更多細節

abstract class Creature { 
     public abstract void makeNoise(); 
    } 

class Monster extends Creature { 
    public void makeNoise() 
    { 
     System.out.println("Raaa!"); 
    } 
} 

class Orc extends Monster { } 

abstract class Myth extends Creature { } 

class Unicorn extends Myth { 
    public void makeNoise() 
    { 
    System.out.println("Neigh!"); 
    } 
} 

Unicorn x = new Unicorn(); 
if (x instanceof Myth) { 
    System.out.println("myth"); 
} 
else { 
    System.out.println("not myth"); 
} 
x.makeNoise(); 

Orc y = new Orc(); 
if (x.getClass() == y.getClass()) { //I need more explanation on this 'getClass()' method 
    System.out.println("yes"); 
} 
else { 
    System.out.println("no"); 
} 
y.makeNoise(); 

我的輸出是:

  • 神話
  • 嘶!
  • Raaa!

它正確嗎?

最後一個問題:

  • 是子類的對象的父類的實例?

回答

0

您的代碼工作正常,輸出也正確。

最後一個問題:

是子類的對象的父類的實例?

爲了明確上述問題,您需要學習繼承概念。 請考慮下面的代碼。我在評論中解釋過

class Super { 
    public void test() { 
     System.out.println("From Super Class TestMethod"); 
    } 
} 

class Sub extends Super { 
    public void subTest() { 
     System.out.println("From the Sub Class Test "); 
    } 
} 

public class SubSuperCheck { 

    public static void main(String[] args) { 
     Sub s = new Sub();// when JVM find this, it will create the memory for 
          // the 
          // two methods test() from Super class and subTest() 
          // from Sub Class 
          // if the reference(Sub s) is also the Sub then we 
          // can access the two methods(test() and subTest()) 
          // if the reference(Super s) then we are able to 
          // access the Super class method only. 
     System.out.println(s.getClass());// getClass() method of Object class 
              // will return the the class name 
              // with which we created the object 
              // here we have created the the 
              // class with Sub. So that we will 
              // get the out put as Sub 
     s.subTest();// Sub class method 
     s.test();// Super class method 
     // if we create in the following way 
     Super s2 = new Sub(); 
     // then we are able to access the Super class method only 
     s2.test();// Okay 
     s2.subTest();// we will get compilation error--The method subTest() is 
         // undefined for the type Super 
    } 

} 
相關問題