java既overload同override?

2008-12-06 12:06 am
class A {
public int f(int i) {return i;}
public int g(int j) {return j;}
}
class B extends A {
public int f(int a) {return a+10;}
public int g(int a, int b) {return a+b;}
}

Which method is overloading?
Which method is overriding?


其實唔多明佢地點樣分?
有冇人可以簡單咁分辨佢地

回答 (1)

2008-12-06 8:24 pm
✔ 最佳答案
method g 是overload, 因為有兩個g 的method同時有效。overload 是如果 幾個method g有不同的parameter/arguemnt,你可以有幾個method g。

method f 是overwrite, 因為parameter相同, class B的method f遮蓋了class A的method f。

你在一個空的folder, 開一個TestProg.java的file, TestProg的內容如下:
public class TestProg{
public static void main(String args[]){
B bObj = new B();
System.out.println("Calling the g(int,init) in subclass B and answer is "+bObj.g(20,100));
System.out.println("Calling the f(int) in subclass B and answer is "+bObj.f(2000));
}
}
class A {
public int f(int i) {return i;}
public int g(int j) {return j;}
}
class B extends A {
public int f(int a) {return a+10;}
public int g(int a, int b) {return a+b;}
}

2008-12-06 12:25:18 補充:
method f 是override, 因為parameter相同, class B的method f遮蓋了class A的method f。


收錄日期: 2021-04-27 15:05:50
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20081205000051KK00816

檢視 Wayback Machine 備份