第4題
題目:
11.class Parent{
12. String Name(){return "ppp";}
13.}
14.public class Son extends Parent{
15. String Name(String name){return name;}
16. public static void main(String[] args) {
17. Parent p=new Son();
18. System.out.println(p.Name());
19. }
20.}
下列何者為結果?
(A) ppp
(B) name
(C) 執行錯誤
(D) 編譯錯誤
你的答案: D
正確答案: A
錯誤
[詳解]
◎ 重载时形参必须相同,Son中形参不同所以没有重载,子类继承了父类的这个方法。因為Son沒有Name()的方法,所以即使p指向Son的物件,還是呼叫Parent的Name()方法。
---------------------------------------------------------------------------------------------------------------------------------------------------
第6題
題目:
Given:
class A {
public A fun() {
return this;
}
}
class B extends A {
public A fun() {
return this;
}
}
class C extends B {
// insert method here
}
Which one method, inserted individually, correctly complete the C class?
(A) public void fun(){}
(B) public int fun(){return 3;}
(C) public B fun(){return this;}
(D) public Object fun(){return this;}
你的答案: B
正確答案: C
錯誤
◎ 重载时形参必须相同,Son中形参不同所以没有重载,子类继承了父类的这个方法。
因为形参相同,所以不算重载,返回值必须相同。这里B可以自动向上转型。
---------------------------------------------------------------------------------------------------------
class Foo {
private int x;
public Foo(int x) {
this.x = x;
}
public void setX(int x) {
this.x = x;
}
public int getX() {
return x;
}
}
public class Gamma {
static Foo fooBar(Foo foo) {
foo = new Foo(100);
return foo;
}
public static void main(String[] args) {
Foo foo = new Foo(300);
System.out.print(foo.getX() + "-");
Foo fooFoo = fooBar(foo);
System.out.print(foo.getX() + "-");
System.out.print(fooFoo.getX() + "-");
foo = fooBar(fooFoo);
System.out.print(foo.getX() + "-");
System.out.print(fooFoo.getX());
}
}
What is the output?
(A) 300-100-100-100-100
(B) 300-300-100-100-100
(C) 300-300-300-100-100
(D) 300-300-300-300-100
你的答案: C
正確答案: B
錯誤
方法的呼叫永遠都是傳值,方法在接到值之後,會另外產生一個空間來存這個值,也就是有兩份值,兩個位址