import java.text.*;public class PersonTest
{  
   public static void main(String[] args)
   {  
      Person[] people = new Person[2];      // fill the people array with Student and Employee objects
      people[0] 
         = new Employee("Harry Hacker", 50000);
      people[1] 
         = new Student("Maria Morris", "computer science");      // print out names and descriptions of all Person objects
      for (int i = 0; i < people.length; i++)
      {  
         Person p = people[i];
         System.out.println(p.getName() + ", "
            + p.getDescription());
      }
   }
}abstract class Person
{  
   public Person(String n)
   {  
      name = n;
   }   public abstract String getDescription();   public String getName()
   {  
      return name;
   }   private String name;
}class Employee extends Person
{  
   public Employee(String n, double s)
   {  
      // pass name to superclass constructor
      super(n);
      salary = s;
   }   //public double getSalary()
  //{  
      ////return salary;
  // }   public String getDescription()
   {  
      NumberFormat formatter
         = NumberFormat.getCurrencyInstance();
      return "an employee with a salary of "
         + formatter.format(salary);
   }   public void raiseSalary(double byPercent)
   {  
      double raise = salary * byPercent / 100;
      salary += raise;
   }   private double salary;
}class Student extends Person
{  
   /**
      @param n the student's name
      @param m the student's major
   */
   public Student(String n, String m)
   {  
      // pass n to superclass constructor
      super(n);
      major = m;
   }   public String getDescription()
   {  
      return "a student majoring in " + major;
   }   private String major;
}1。抽象类有何作用,为什么要定义“abstract class Person”
2。为什么要定义为“public abstract String getDescription();”,不定义成抽象方法可以吗?
3。这句语句我不太理解:“Person[] people = new Person[2];”
高手指教!

解决方案 »

  1.   

    1。因为Person里有抽象方法,没有定义的,要到derived class里去定义2。没有定义的就要是abstract,有abstract方法的就是abstract class了3。int []a = new int[2]理解吗,一样的意思,就是一个Person的数组,元素是Person而已
      

  2.   

    1、abstract关键字是抽象类的声明,表明该类是一个抽象类,必须被继承后才能实例化。
    2、抽象类中至少要有一个抽象方法,否则就不是抽象类了。
    3、虽然抽象类是不能被实例化的,但是“Person[] people = new Person[2];”并不是直接实例化一个抽象类,而是实例化了一个抽象类的数组,因为在java中数组也是一个对象,也需要被实例化。而在该代码以下的还有这样两个实例化:
    people[0]
              = new Employee("Harry Hacker", 50000);
    people[1] 
             = new Student("Maria Morris", "computer science");
    这两句代码分别实例化了数组中具体的元素,而这两个元素分别都是继承Person类的实体类,因此可以被实例化。
      

  3.   

    1.抽象类就是一个不能够生成对象的类 abstract是抽象类的关键字,抽象类一般是为类派生出实际的类而存在的,比如我们就可以从person中派生一个学生类来.
    2.只要是没有实体的方法就是抽象方法~~所以我们必须加上abstract这个关键字,说明是个抽象方法
    3.Person[] people = new Person[2]; 是生成一个有两个引用person类的数组
    因为基类的引用可以指向派生类,这其实就是抽象类存在的意义
      

  4.   

    抽象类中含有抽象方法,抽象方法是只给出方法声明但没有方法体的方法。
    子类在继承抽象类时,必须重构其父类的抽象方法,给出具体的定义。
    抽象类的主要作用是描述抽象概念,形成更清晰的类层次体系。抽象类在程序的分析
    设计阶段扮演着重要的角色,因为在早期我们尚无法确定一些行为的实现策略时,可以将她们定义为
    抽象方法,并用抽象类描述相应的实体。
    3.定义了一个Person类型的数组,数组元素有2个