java中的继承问题

// 定义一个Earth类
public class Earth
{
protected String name;
protected int age;
public Earth(String name, int age)
{
this.name = name;
this.age = age;
}
}

// 定义一个Human类并继承Earth类
public class Human extends Earth
{
protected String name; // 由于在父类中已经定义,所以可以不需要
protected int age;
protected double weight;

public Human(String name, int age)
{
this.name = name;
this.age = age;
}​
}


在编译时会出现以下问题:
Human.java:10: 错误: 无法将类 Earth中的构造器 Earth应用到给定类型;
{
需要: String,int
找到: 没有参数
原因: 实际参数列表和形式参数列表长度不同

原因分析:这是因为没有调用父类的两个参数的构造器,在没有明确指定调用父类哪个构造器的时候默认调用的是无参的构造器,但是父类中没有无参构造器,因此会报这种错误
解决方式1:super(name.age)
解决方式2:在父类中添加一个无参构造器

原文地址:https://www.cnblogs.com/qadyyj/p/5488293.html