java多态性实例

来源:互联网 发布:windows怎么开发ios 编辑:程序博客网 时间:2024/05/23 13:02
import java.util.*;public class PersonTest{public static void main(String args[]){Person[] people=new Person[2];people[0]=new Employee("Harry",50000,1989,0,1);//多态性people[1]=new Student("Maria","computer science");//多态性for(Person p:people){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,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 getHire(){return hireDay;}public String getDescription(){return String.format("an employee with asalary of $%.2f",salary);//对浮点格式化,返回精度为2的浮点数}public void raiseSalary(double byPercent){double raise=salary*byPercent/100;salary+=raise;}private double salary;private Date hireDay;}class Student extends Person{public Student(String n,String m){super(n);major=m;}public String getDescription(){return "a student majoring in"+major;}private String major;}

原创粉丝点击