07课堂问题整理

作业归档7 继承与接口

完成课件中的动手动脑的或需要验证的相关内容。

1、运行 TestInherits.java 示例,观察输出,注意总结父类与子类之间构造方法的调用关系修改Parent构造方法的代码,显式调用GrandParent的另一个构造函数,注意这句调用代码是否是第一句,影响重大!

代码:

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 {

    public static void main(String args[]) {

        Child c = new Child();

    }

}

运行结果:

GrandParent Created.

Parent Created

Child Created

当把第一个//super("Hello.Grandparent.");//去掉后,运行结果是

GrandParent Created.String:Hello.Grandparent.

Parent Created

Child Created

说明super可以调用父类的构造方法。

若是把第二个//super("Hello.Grandparent.");//去掉后,将会出现编译错误Constructor call must be the first statement in a constructor说明要用super调用父类构造方法,必须是在子类构造方法中的第一句。

为什么子类的构造方法在运行之前,必须调用父类的构造方法?

子类是通过父类继承过来的,所以子类有父类的属性和方法,如果不调用父类的构造方法,无法初始化父类中定义的属性,无法给父类的属性分配内存空间。

2、请自行编写代码测试以下特性(动手动脑):在子类中,若要调用父类中被覆盖的方法,可以使用super关键字。

public class YanZheng {

    public static void main(String []args){

     Pear pear=new Pear();

     pear.output();

    }

}

class Apple{

public void output(){

System.out.println("父类:苹果。");

}

}

class Pear extends Apple{

public void output(){

super.output();

System.out.println("子类:梨。");

}

}

运行结果:

父类:苹果。

子类:梨。

转载于:https://www.cnblogs.com/hjy415/p/6055459.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值