題目一
class Base{
Base(){
System.out.println("Base");
}
}
public class Checket extends Base{
Checket(){
System.out.println("Checket");
super();
}
public static void main(String argv[]){
Checket a = new Checket();
}
}
輸出是什么? 是 compile time error. super() 必須放在前面.
放在前面之后,輸出為 Base Checket
題目二
import java.util.Date;
public class Test extends Date{
public static void main(String[] args) {
new Test().test();
}
public void test(){
System.out.println(super.getClass().getName());
}
}
返回的結(jié)果是 Test
因?yàn)閟uper.getClass().getName() 調(diào)用了父類的 getClass() 方法, 返回當(dāng)前類
如果想得到父類的名稱,應(yīng)該用如下代碼:
getClass().getSuperClass().getName()
題目三
public abstract class Car {
String name = "Car";
public String getName(){
return name;
}
public abstract void demarre();
}
public class B extends Car{
String name = "B";
public String getName(){
return name;
}
public void demarre() {
System.out.println(getName() + " demarre");
}
}
public class C extends B{
String name = "C";
public String getName(){
return name;
}
public void demarreWithSuper() {
System.out.println(super.getName() + " demarre");
}
public void demarreNoSuper() {
System.out.println(getName() + " demarre");
}
}
public class D extends B{
public String getName(){
return name;
}
public void demarreNoSuper() {
System.out.println(getName() + " demarre");
}
}
public class Test {
public static void main(String[] args) {
B b = new B();
b.demarre();
Car bCar = new B();
bCar.demarre();
C c = new C();
c.demarre(); // c 里并沒有定義這個函數(shù)
c.demarreWithSuper();
c.demarreNoSuper();
D d = new D();
d.demarre();
transfer(c); // TransferC
transfer((B)c); // TransferB
transfer(d); // TransferB
}
public static void transfer(B b){
System.out.println("TransferB");
b.demarre();
}
public static void transfer(C c){
System.out.println("TransferC");
c.demarre();
}
}
}
輸出是 B demarre B demarre C demarre B demarre C demarre B demarre TransferC C demarre TransferB C demarre TransferB B demarre