小弟刚学java,看了书上的这段代码有点不懂
import java.util.*;public class ManagerTest
{
   public static void main(String[] args)
   {
      // construct a Manager object
      Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
      boss.setBonus(5000);      Employee[] staff = new Employee[3];      // fill the staff array with Manager and Employee objects      staff[0] = boss;
      staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
      staff[2] = new Employee("Tommy Tester", 40000, 1990, 3, 15);      // print out information about all Employee objects
      for (Employee e : staff)
         System.out.println("name=" + e.getName()
            + ",salary=" + e.getSalary());
   }
}class Employee
{
   public Employee(String n, double s, int year, int month, int day)
   {
      name = n;
      salary = s;
      GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
      hireDay = calendar.getTime();
   }   public String getName()
   {
      return name;
   }   public double getSalary()
   {
      return salary;
   }   public Date getHireDay()
   {
      return hireDay;
   }   public void raiseSalary(double byPercent)
   {
      double raise = salary * byPercent / 100;
      salary += raise;
   }   private String name;
   private double salary;
   private Date hireDay;
}class Manager extends Employee
{
   /**
      @param n the employee's name
      @param s the salary
      @param year the hire year
      @param month the hire month
      @param day the hire day
   */
  public Manager(String n, double s, int year, int month, int day)
   {
      super( n,  s,  year,  month,  day);
      bonus = 0;
   }   public double getSalary()
   {
      double baseSalary = super.getSalary();
      return baseSalary + bonus;
   }   public void setBonus(double b)
   {
      bonus = b;
   }   private double bonus;
}在这段程序中,是不是子类Manager不能直接使用超类Employee的构造方法呢?我把Employee中的private double salary;改成public double salary;
  把子类Manager中
 public double getSalary()
   {
      double baseSalary = super.getSalary();
      return baseSalary + bonus;
   }
改成
public double getSalary()
   {
      double baseSalary = salary;
      return baseSalary + bonus;
   }
不行呢?不是public 定义的在所有类中都可以使用吗?

解决方案 »

  1.   

    salary是父类的私有属性,不能直接访问的,编译肯定不通过,楼主你可以试试这里必须使用super.getSalary(),如果使用getSalary()就调用了Manager的getSalary()方法了,肯定抛堆栈溢出异常
      

  2.   

    这里用到的是类的继承与多态机制,当你本身的对象是Manager的对象时,编译器会恰当的调用Manager其构造函数。
     你说的:我把Employee中的private double salary;改成public double salary; 这个不管是私有的还是公有的在本类中你都可以用,出了这个类你就不能直接的拿来用。
    但将子类中的super.getSalay()改成salay是不对的。salary是Employee类的私有变量,你只能通过继承超类的public double getSalary() 方法才能调用salary的值。
      

  3.   

    我看书上写的 说public 定义的实例域许任何类的任何方法进行调用。
    为什么我把Employee中的private double salary;改成public double salary;
    仍然只能在Employee中使用,而在Manager这个类中不能使用salary呢?
      

  4.   

    这里不光是public 或者private 的问题。还有继承的问题。建议LZ认真的看下继承这部分。