java子类继承父类问题 - 爱问答

(爱问答)

java子类继承父类问题

java课作业题

父类 Author只有有参构造方法

class Author{

    String name;

    String email;

    char gender;

    public Author(String name,String email,char gender){

    this.name=name;

    this.email=email;

    this.gender=gender;

}

}

子类 book只有有参构造方法

class Book extends Author{

    String name;

    Author author;

    double price;

    public Book(String name,Author author,double price){

    super(name,email,gender);

    this.name=name;

    this.author=author;

    this.price=price;

}

在主函数中

Author cA=new Author(name,email,gender);

Book zB=new Book(name,cA,price);


super()一定要写和cA里的参数一样吗,cA的参数变了,那不是还要改super()里的参数吗

java继承中对构造函数是不继承的。

以下是例子:

public class FatherClass {
public FatherClass() {
      System.out.println(100);
}

public FatherClass(int age) {
     System.out.println(age);
}

}

public class SonClass extends FatherClass{

       public SonClass() {
        }
       public SonClass(int c) {
                System.out.println(1234);
       }
 
public static void main(String[] args) {

 FatherClass f = new FatherClass(28);
 SonClass s = new SonClass(66);

}
}

编译后执行结果如下是什么呢?

分析:1. FatherClass f = new FatherClass(28);这句没有必要解释

2.SonClass s = new SonClass(66);执行这句时,调用

public SonClass(int c) {
                System.out.println(1234);
       }


在这个构造函数中,等价于

public SonClass(int c) {

               super();//必须是第1行,否则不能编译
                System.out.println(1234);
       }

所以结果是    100
                        1234

3.如果子类构造函数是这样写的

public SonClass(int c) {

               super(22);//必须是第1行,否则不能编译


ca的参数变了,为何要改super()的参数?


cA已经和zB绑定到一起了

相关标签:java

下一篇:省人力资源社会保障厅网站http://www.gdhrss.gov.cn报名入口在哪里。急急急!!

上一篇:pci通道问题

热门标签:
excel 网盘 破解 word dll
最新更新:
微软重新评估新的Outlook的使用时机 联想推出搭载联发科Helio G80芯片组的Tab M9平板 英特尔创新大赛时间确定! 微软Edge浏览器在稳定渠道中推出Workspaces功能 英伟达RTX4060TiGPU推出MaxSun动漫主题! 谷歌地图为用户提供了街景服务! GameSir 在T4 Kaleid中推出了一款出色的控制器! 微软开始在Windows 11 中测试其画图应用程序的新深色模式! LG电子推出全球首款无线OLED电视 英伟达人工智能芯片崭露头角! Steam Deck可以玩什么游戏-Steam Deck价格限时优惠 雷蛇推出CobraPro鼠标 Kindle电子阅读器可以访问谷歌商店吗 Windows10如何加入组策略 window10图片查看器怎么没有了?