2016-04-23 50 views

回答

1

子類中的重載沒有限制。例如,我可以有:

public class A { 
public String test(String input) { 
    //do something 
} 
} 

public class B extends A { 
public String test(String input, String input2) { 
    //do something 
} 
} 

B testInstance = new B(); 
testInstance.test("one", "two"); 
testInstance.test("one"); 

對於這樣的問題,您可以隨時嘗試自己並找出答案。

1

總而言之 - 是的。你可以在子類中重載方法。例如: -

public class Parent { 
    public void print(String s) { 
     System.out.println("That was a string: " + s); 
    } 
} 

public class Child { 
    public void print(int i) { 
     System.out.println("That was an int: " + i); 
    } 
} 

public class Main { 
    public static void main(String[] args) { 
     Child c = new Child(); 
     c.print("hello"); // prints "That was a string: hello" 
     c.print(7); // prints "That was an int: 7" 
    } 
} 
0

當重載的方法,它基本上與創建與其他同名沒有直接關聯一個全新的方法,它是重要的簽名。 所以如果你在具有不同簽名的子類中創建一個方法,它將被編譯器視爲該類的不同和新方法,所以它不會將它與超類的方法關聯起來。

0

在子類中可以重載。如果使用不同參數的超類創建一個名稱相同的方法,那麼它將被視爲單獨的方法。 Sub類也會有超類的方法,所以根據參數類型在編譯時決定要調用的方法。在編譯時聲明哪個方法被稱爲靜態多態。這裏的例子 -

Class A{ 
    void m1(int x){ 
     System.out.println("m1 in A"); 
    } 
} 
Class B extends A 
{ 
    void m1(String str) 
    { 
     System.out.println("m1 in B"); 
    } 
} 
Public Class Test 
{ 
    public static void main(String[] aa) 
    { 
     B b = new B(); 
     b.m1(10); 
     b.m1("Hello World!!") 
    } 
} 

希望這會有所幫助。