java核心技术 抽象类 程序清单5-4 PersonTest.java

    xiaoxiao2021-03-25  109

    测试类

    public class PersonTest { public static void main(String[] args) { //这里就是抽象类的声明,但不能将抽象类实例化 ,实例化的是Person类的子类 //这里也证明了,父类引用可以引用,子类对象,因为父类引用的方法不会超过子类对象的方法,但反之不行 Person[] people = new Person[2]; people[0] = new Employee("Harry Hacker", 50000, 1989, 10, 1); people[1] = new Student("Maria Morris", "computer science"); //这里应该是使用了方法的重写?有想法者可留言 for(Person p: people){ System.out.println(p.getName()+", "+p.getDescription()); } } }

    抽象类 Person类

    public abstract class Person { //包含一个或多个抽象方法的类被称为抽象类,由abstract关键字修饰。 //通用的作用域和方法也放到这里,抽象类不能被实例化,但可以被声明 public abstract String getDescription(); private String name; public Person(String n){ name = n; } public String getName(){ return name; } }

    Employee类

    import java.util.Date; import java.util.GregorianCalendar; public class Employee extends Person{ private double salary; private Date hireDay; public Employee(String n,double s,int year,int month,int day){ super(n); salary = s; GregorianCalendar calendar = new GregorianCalendar(year,month-1,day); hireDay = calendar.getTime(); } public double getSalary(){ return salary; } public Date getHireDay(){ return hireDay; } //重写父类方法,返回一个格式化的字符串 public String getDescription(){ return String.format("an employee with a salary of $%.2f", salary); } }

    Student类

    public class Student extends Person{ private String major; public Student(String n,String m){ super(n); major = m; } public String getDescription(){ return "a student majoring in "+major; } }

    运行结果: Harry Hacker, an employee with a salary of $50000.00 Maria Morris, a student majoring in computer science

    转载请注明原文地址: https://ju.6miu.com/read-9055.html

    最新回复(0)