从派生类调用超类:

时间:2015-07-24 18:13:34

标签: java

当我为子类创建引用对象并尝试输出引用对象时,我只从超类获得输出,并且它不会显示子类中的任何内容。为什么?

//超类代码:

public class Employee 
{
    private String name;
    private Date hireDate;

    public Employee()
    {
        name="no name yet";
        hireDate=new Date("January",1,1000);
    }
    public Employee(String theName,Date theDate)
    {
        if(theName==null||theDate==null)
        {
            System.out.println("Error1");
            System.exit(0);
        }
        else
            name=theName;
            hireDate=new Date(theDate);
    }
    public Employee(Employee originalObject)
    {
        name=originalObject.name;
        hireDate=new Date(originalObject.hireDate);
    }
    public String getName()
    {
        return name;
    }
    public Date getHireDate()
    {
        return new Date(hireDate);
    }
    public void setName(String newName)
    {
        if(newName==null)
        {
            System.out.println("Error2");
            System.exit(0);
        }
        else 
            name=newName;
    }
    public void setHireDate(Date newDate)
    {
        if(newDate==null)
        {
            System.out.println("Error3");
            System.exit(0);
        }
        else 
            hireDate=new Date(newDate);
    }
    public String toString()
    {
        return(name+ " "+hireDate.toString());
    }
    public boolean equals(Employee otherEmployee)
    {
        return((name.equals(otherEmployee.name))&&(hireDate.equals(otherEmployee.hireDate)));
    }
}

/////////////////////////////////////////////////////////////////////////

//sub class code:

public class SalariedEmployee extends Employee 
{
    private double salary; //annually
    public SalariedEmployee()
    {
        super();
        salary=0;
        System.out.println("hi");
    }
    public static void main(String[]args)
    {
        SalariedEmployee s=new SalariedEmployee();
        System.out.println(s);
    }
}


//Thank u....

1 个答案:

答案 0 :(得分:0)

 System.out.println(s);

这使用对象的toString()方法。您还没有在子类中重写此方法,因此您只能看到超类实现的输出。

例如,您可以添加SalariedEmployee类:

public String toString(){
  return super.toString() + ",salary:" +salary;
}