2016-07-22 20 views
1

我確定這是一個簡單的問題,但我不知道答案。首先,是否有可能做這樣的事情?我可以在不重寫子類的情況下使用超類中的方法嗎?

public class Entity { 


public void sayHi() { 
     System.out.println(「Hi there!」); 
    } 
} 

public class Person extends Entity { 
    public void sayHi() { 
     System.out.println(「I’m a person!」); 
    } 
} 

打印出來的地方是:HI there!我是一個人! 這只是一個例子,但這可能嗎?如果是這樣,我該怎麼做?因爲這樣,實際的打印輸出將是「我是一個人!」。 Person中的sayHi()方法是否必須有自己的打印輸出:「Hi There!」爲了這個工作?

如果您有任何問題請留下評論,我會盡我所能。謝謝。

+0

使用'super.sayHI()''中的sayHi()'人'的' – emotionlessbananas

回答

5

是的,您只需從子類中的方法調用超類中的方法即可。

請參閱The Java™ Tutorials - Using the Keyword super

public class Entity { 
    public void sayHi() { 
     System.out.println("Hi there!"); 
    } 
} 
public class Person extends Entity { 
    @Override 
    public void sayHi() { 
     super.sayHi(); 
     System.out.println("I’m a person!"); 
    } 
} 
+0

又名[* Decorator模式*](https://en.wikipedia.org/wiki/Decorator_pattern)。 – Bohemian

+0

@Andreas謝謝!我知道有一個簡單的答案。 @覆蓋是必要的嗎? –

+0

'@ Override' *是否必要*?不,但**高度鼓勵,因爲它有助於捕捉編碼錯誤。 – Andreas

1
 public class Entity { 
     public void sayHi() { 
      System.out.print("Hi there!"); 

     } 
    } 
    public class Person extends Entity { 
     super.sayHi(); 
System.out.print("I’m a person!"); 
    } 

I think this may helps you. 
+0

'打印出的地方是:你好!我是一個人'請仔細閱讀問題 – emotionlessbananas

+0

Hi @AsteriskNinja,我剛剛更新了代碼,只是看一次。 – user4342532

+0

@ Root_1989謝謝!這工作完美。 –

0

關於安德烈亞斯anwser,有沒有加 '超級' 通過Java反射的方式:

public class Entity { 
    public void sayHi() { 
     System.out.println("Hi there!"); 
    } 
} 

public class Person extends Entity { 
    public void sayHi() { 
     System.out.println("I’m a person!"); 
    } 
} 

public class Tester { 
    public static void main(String[] args) throws Throwable { 
     Person x = new Person(); 
     MethodHandle h1 = MethodHandles.lookup().findSpecial(x.getClass().getSuperclass(), "sayHi", 
       MethodType.methodType(void.class), 
       x.getClass()); 

     h1.invoke(x); 
     x.sayHi(); 
    } 
} 
+0

感謝您的回答!這種方法比其他方法更復雜,所以我不認爲我會使用它,但我會在以後牢記它。 –

相關問題