继承和super关键字

继承,super关键字

public class TestSuperSub {
    public static void main(String[] args) {
        Sub s1 = new Sub();
        System.out.println();
        Sub s2 = new Sub(1);
        System.out.println();
        Sub s3 = new Sub("a");
    }
}

class Super {
    public Super() {
        System.out.println("super");
    }

    public Super(String string) {
        System.out.println("superstr");
    }
}

class Sub extends Super{
    public Sub(){
        System.out.println("sub");
    }

    public Sub(int i) {
        this();
        System.out.println("subint");
    }

    public Sub(String string) {
        super(string);
        System.out.println("substr");
    }
}

结果:

在这里插入图片描述

在实例化子类对象时,会优先实例化父类。如果子类的构造函数中有通过super关键字调用父类的构造方法,在实例化父类时会使用这个指定的构造方法,如果没有指定,就会默认使用空参的构造方法。

在这里插入图片描述

若一个父类中只有一个或多个带参数的构造方法,那么在写其子类的构造方法时必须先通过super调用父类的构造方法才能完成子类的构造方法而且super只能写在子类构造方法体内的第一行。


父类的引用可以调用子类中重写的父类的方法,但不能调用子类中独有的方法,即不能调用父类中不存在,子类中存在的方法。

class Father{
    public void eat(){
        System.out.println("father eat");
    }
}

class Son extends Father{
    @Override
    public void eat() {
        System.out.println("son eat");
    }

    public void work(){
        System.out.println("son work");

    }
}

public class FatherSon {
    public static void main(String[] args) {
        Father f1 = new Son();
        f1.eat();
//        f1.work();
    }
}

在这里插入图片描述

当父类引用调用eat()时,实际上运行的是子类重写的eat()函数。

在这里插入图片描述

父类不能调用子类独有的方法。

发布了5 篇原创文章 · 获赞 1 · 访问量 227

猜你喜欢

转载自blog.csdn.net/qq_41551830/article/details/104402049
今日推荐