JAVA课堂动手动脑

实验心得:

1.

package test;

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

}

class Parent extends Grandparent
{
    public Parent()
    {
        //super("Hello.Grandparent.");
        System.out.println("Parent Created");
        // super("Hello.Grandparent.");
    }
}

class Child extends Parent 
{
    public Child()
    {
        System.out.println("Child Created");
    }
}

public class TestInherits 
{
    @SuppressWarnings("unused")
    public static void main(String args[])
    {
        Child c = new Child();
    }
}

通过 super 调用基类构造方法通过 super 调用基类构造方法,必须是子类构造方法中的第一个语句。

2.在子类中,若要调用父类中被覆盖的方法,可以使用super关键字。

3.当子类与父类拥有一样的方法,并且让一个父类变量引用一个子类对象时,到底调用哪个方法,由对象自己的“真实”类型所决定,这就是说:对象是子类型的,它就调用子类型的方法,是父类型的,它就调用父类型的方法。

4.类型转换

package test;

class Mammal{}
class Dog extends Mammal {}
class Cat extends Mammal{}

public class TestCast
{
    public static void main(String args[])
    {
        Mammal m;
        Dog d=new Dog();
        Cat c=new Cat();
        m=d;
        //d=m;
        d=(Dog)m;
        //d=c;
        //c=(Cat)m;

    }
}

 子类对象可以直接赋给基类变量。

基类对象要赋给子类对象变量,必须执行类型转换,

其语法是: 子类对象变量=(子类名)基类对象名;

猜你喜欢

转载自www.cnblogs.com/shnm/p/9906221.html