抽象类

来源:互联网 发布:mysql c开发工具 编辑:程序博客网 时间:2021/06/19 15:23

public class FirstSample{
    public static void main(String[] args){
        Person[] people=new Person[2];
       
        people[0]=new Employee("A",500);
        people[1]=new Student("B","CS");
       
        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){
        super(n);
        salary=s;
    }
    public String getDescription(){
        return String.format("an employee with a salary of $%.2f",salary);
    }
   
    private double salary;
}

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

原创粉丝点击