我正在尝试访问比我高两级的抽象类中的构造函数。
public abstract class Person{
protected String name;
public Person(String name){
if name.length() <= 12)
this.name = name;
else
this.name = name.substring(0,12);
}
public final String returnName(){
return name;
}
}
public class employee extends person{
public employee(string firstname, string gender){
super(firstname);
this.gender =gender;
}
}
public class dependent extends employee{
public dependent(string firstname, string gender, string relation){
super(firstname);
super(gender);
this.relation = relation;
}
如何从依赖类(下面两个级别)调用抽象类的构造函数?
好的,首先,以下是将两个参数传递给 Employee 构造函数的方法:
super(firstname, gender);
其次,无需从依赖构造函数调用 Person 构造函数。当 Dependent 调用 Employee 构造函数时,这将自动发生,因为 Employee 构造函数随后调用 Person 1。
您要查找的内容如下所示,请注意,方法参数以大写和驼峰大小写开头,并以小写字母命名。字符串必须是大写String name
,也请注意,您已经在name
上引入了受保护的成员作用域请参阅以下关于在 Java 中的含义的文章,默认、公共、受保护和私有之间的区别
public abstract class Person
{
protected String name;
public Person(String name)
{
if (name.length() <= 12)
{
this.name = name;
}
else
{
this.name = name.substring(0, 12);
}
}
public final String returnName()
{
return name;
}
}
public class Employee extends Person
{
private String gender = null;
public Employee(String firstName, String gender)
{
super(firstName);
this.gender = gender;
}
}
public class Dependent extends Employee
{
private String relation = null;
public Dependent(String firstName, String gender, String relation)
{
super(firstName, gender);
this.relation = relation;
}
}
如果您需要访问这些关系和性别,则需要添加访问这些方法
试试这个:
public class employee extends Person{
public employee(String firstname, String gender){
super(firstname);
this.gender =gender;
}
}
public class dependent extends employee{
public dependent(String firstname, String gender, String relation){
super(firstname,gender);
this.relation = relation;
}