2016-07-07 55 views
0

代碼1:CODE1Overriding-爲什麼長被稱爲的不是int

class Tyre 
{ 
    public void front() throws RuntimeException 
    { 
     System.out.println("Tire"); 
    } 
    public void front(int a) 
    { 
     System.out.println("Radial Tire with int in tyre"); 
    } 
    public void front(long a) 
    { 
     System.out.println("Radial Tire with long"); 
    } 
} 

class RadialTyre extends Tyre 
{ 
    public void front() 
{ 
     System.out.println("Radial Tire"); 
    } 
    public void front(int a) 
    { 
     System.out.println("Radial Tire with int"); 
    } 
} 

class Test 
{ 
     public static void main(String... args) 
     { 
       Tyre t = new RadialTyre(); 
       int a = 10; 
       t.front(a); 
     } 
} 

O/P:-Radial輪胎爲int

代碼2: -

class Tyre 
{ 
    public void front() throws RuntimeException 
    { 
     System.out.println("Tire"); 
    } 

    public void front(long a) 
    { 
     System.out.println("Radial Tire with long"); 
    } 
} 

class RadialTyre extends Tyre 
{ 
    public void front() 
{ 
     System.out.println("Radial Tire"); 
    } 
    public void front(int a) 
    { 
     System.out.println("Radial Tire with int"); 
    } 
} 

class Test 
{ 
     public static void main(String... args) 
     { 
       Tyre t = new RadialTyre(); 
       int a = 10; 
       t.front(a); 
     } 
} 

O/p for code2: - 長徑向輪胎

爲什麼在code1中調用child class int方法而在code2中調用父類long方法?如果這是由於擴大而發生的,那麼爲什麼case1擴展不會發生?在code1中爲什麼當父類中已經存在一個int方法時調用子類的int方法?

回答

2

爲什麼在code1中調用child class的int方法而在code2中調用父類的long方法?

因爲你沒有覆蓋,您超載。過載是指方法名稱相同但簽名不同(即long參數與int)。

既然你是指類型Tyre而不是RadialTyre,並沒有覆蓋該方法front,它選擇只有一個Tyre意識到:在一個這需要long參數。

class RadialTyre extends Tyre { 
    // This is an overLOAD, same method name but different parameter type 
    public void front(long a) { 
     System.out.println("Radial Tire with int"); 
    } 

    // This is an overRIDE, same method name with same signature 
    public void front(int a) { 
     System.out.println("Radial Tire with long - override"); 
    } 
} 

在編碼1爲什麼當一個int方法父類中已經存在的子類int方法被調用?

這是如何壓倒一切的作品。如果一個類擴展了另一個類並覆蓋了一個或多個超類方法,那麼這些類將被調用。

+0

感謝您回答我的第一個問題。如果Tire不知道RadialTyre,那麼爲什麼RadialTyre的int方法在代碼1中被執行而不是來自Tyre類的int方法?這些int方法肯定會被覆蓋。 – Snehal

+0

@Snehai也回答了第三個問題。但是,我的主要語言不是英語,我從來沒有聽說過「擴大」。我正在維基百科上閱讀它,它似乎與您的問題沒有關係。你能詳細說明嗎? – BackSlash

+0

你可以參考這個理解拓寬https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html – Snehal

相關問題