2014-03-12 54 views
25

Class Arun()方法和接口B也有run()方法。問題很簡單,run()方法在Main類中被覆蓋,我們將如何證明這一點?爲什麼在這段代碼中沒有衝突(編譯時錯誤)?哪種方法被覆蓋?

class A{ 
    void run(){System.out.println("A class");} 
} 

interface B{ 
    void run(); 
} 

class Main extends A implements B{ 
    public static void main(String args[]){   
     Main m = new Main(); 
     m.run(); 
    } 

    // Overridding method 
    public void run(){ 
     System.out.println("run method"); 
    } 
} 
+0

非常好奇地等待一些專家的回答 –

回答

25

Arun被覆蓋,的Brun被實現。由於B是一個接口,它只說明你的對象如何對其他對象進行操作,並且本身不強制執行任何操作。

+1

所以在'Main'中基本''運行''覆蓋'A'中的'run'會同時執行'run 'B'的? – mangusta

+0

是的。任何使用'Main'的人都可以通過'B'接口看到'Main'會提供一個'run'方法 - 如果這個方法是從基類繼承的或者由Main實現的, 'Main'的用戶。 – Smutje

2

沒有衝突,因爲兩種方法都有相同的簽名。接口中的方法聲明不會被覆蓋,因爲它們沒有實現任何東西。所以在這種情況下,類A中的run方法被覆蓋。

另一方面,當推薦重寫方法時,鼓勵您使用@Override註釋,例如

@Override 
public void run() { 
    .... 
} 
+2

當實現接口方法時,也鼓勵您使用'@ Override'。 –

2

什麼將被稱爲是

public void run(){ 
    System.out.println("run method"); 
} 

爲什麼?

你正在實施的interface Brun而你也覆蓋A實現它。

如果您刪除最後一個run()執行並刪除implements B, run()將被調用。

2

接口B表示任何實現它的類都必須有一個run方法。 Main擴展A並繼承Arun()方法。

主要滿足B接口的要求有一個運行方法。 Main中的run方法將覆蓋A類中的run()方法。

// This is a class with a run method. 
class A{ 
    void run(){System.out.println("A class");} 
} 

// Anything implementing this interface must have a run method. 
interface B{ 
    void run(); 
} 

// This class is an extension of A (and therefore has A's run() method) 
// This class implements B and must have a run method, which it does, because it has A's 
class Main extends A implements B{ 
    public static void main(String args[]){   
     Main m = new Main(); 
     m.run(); 
    } 

    // This method then overrides the run Method it inherited from A 
    // And this method meets the requirement set by implementing B. 
    public void run(){ 
     System.out.println("run method"); 
    } 
} 
+0

這解釋了爲什麼沒有編譯錯誤,仍然是更好的解釋預期 –

1

查看此鏈接...

你會知道比我們告訴更多...

方法http://docs.oracle.com/javase/tutorial/java/IandI/override.html

+6

鏈接到源不是一個好的答案。請解釋。 – Maroun

+1

@MarounMaroun複製並粘貼該源中可用的東西沒有任何意義。此外,給出的解釋相當不錯。 –

+1

解釋wwhy只有鏈接的答案是不鼓勵的:[僅鏈接答案](http://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-答案)。 – Keppil

3

run()界面B會be Implemented in class Main by 覆蓋方法A類

增加一個額外的點,

它,你會不會寫在子類Mainrun()方法,您將無法獲得著名的「未實現的方法」的錯誤。對於非公開方法的類A的public方法,您將得到編譯器錯誤:繼承的方法無法隱藏公共抽象方法。

這是因爲methods of interface are public by default,你不能用default (package private)訪問修飾符隱藏它。

樣品:

class A{ 
    public void run() { 
     System.out.println("This method will be inherited."); 
    } 
} 

interface B{ 
    void run(); 
} 

class Main extends A implements B{ 
    public static void main(String args[]){   
     Main m = new Main(); 
     m.run(); 
    } 
} 

OUTPUT : This method will be inherited.

在上面的代碼情況下,run()方法是從A類繼承,將實現接口B.的run()方法

0

超類的方法總是叫作爲overridden方法,而子類方法被稱爲overriding方法。

最後的方法cannot be覆蓋。 [如果超類的方法是最終的]
最終方法can覆蓋。 [閱讀它的語法方式。這種方法在子類中是最終的,但是超類的方法並不是最終的]