继承条件下构造条件调用

class Grandparent {
    Grandparent(){
    System.out.println("GrandParent Created.");
    }
    Grandparent(String string) {
        System.out.println("GrandParent Created.String:" + string);
    }

}
class Parent extends Grandparent{
    Parent(){
        //super("Hello.Grandparent.");
        System.out.println("Parent Created");
        //super("Hello.Grandparent.");
    }
}
class Child extends Parent {
    Child(){
        System.out.println("Child Created");
    }
}
public class TestInherits {
    public static void main(String args[]){
        Child c = new Child();
    }
}

  上述程序中主方法只创建了一个Child类的对象,在对象创建时默认使用了super()方法调用父类的无参构造方法。若是只将第一个//super("Hello.Grandparent.");解注释,则运行结果中第一行会变成GrandParent Created.String:Hello.Grandparent.。而只将第二个解注释,则编译器会报错。所以,通过 super 调用基类构造方法,必须是子类构造方法中的第一个语句。

 

同时关于类型转换问题

 子类对象可以直接赋给基类变量。 基类对象要赋给子类对象变量,必须执行类型转换, 其语法是: 子类对象变量=(子类名)基类对象名; 如果类型转换失败,Java会抛出ClassCastException异常。

  可以使用instanceof运算符判断一个对象是否可以转换为指定的类型: Object obj="Hello"; if(obj instanceof String) System.out.println("obj对象可以被转换为字符串");

 

posted on 2018-11-04 20:25  哈弗h6  阅读(74)  评论(0编辑  收藏  举报

导航