构造函数有两个类java

时间:2014-11-18 05:25:36

标签: java constructor

我试图访问一个高两级的抽象类中的构造函数。

    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;
        }

如何从依赖类(下面两个级别)调用抽象类的构造函数?

3 个答案:

答案 0 :(得分:0)

试试这个:

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;
        }

答案 1 :(得分:0)

好的,首先,以下是将两个参数传递给Employee构造函数的方法:

super(firstname, gender);

其次,不需要从Dependent中调用Person构造函数。当Dependent调用Employee构造函数时,这将自动发生,因为Employee构造函数然后调用Person 1。

答案 2 :(得分:0)

您正在寻找的是类似下面的内容,请注意类以小写和驼峰大小写开始,方法参数用小写字母盯着。字符串必须是大写的String name,请注意您已在name上引入了受保护的成员范围 请参阅以下关于含义In Java, difference between default, public, protected, and private

的文章
  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;
    }
  }

如果您需要访问这些

,则需要添加访问关系和性别的方法