Java基础四 抽象类

package abstractClasses;

public abstract class Person {
    public abstract String getDescription();
    private String name;

    public Person(String name)
    {
        this.name=name;
    }
    public String getName()
    {
        return name;
    }
}

以上代码定义了一个抽象类Person,抽象类不能实例化,例如表达式 new Person("Vince Vu")是错误的,但可以创建一个子类对象。

下面定义一个扩展抽象类Person的具体子类Student。

package abstractClasses;

public class Student extends Person {

    private String major;

    public Student(String name,String major)
    {
        super(name);
        this.major=major;
    }
    public String getDescription()
    {
        return "a atudent majoring in " + major;
    }
}

因为在Student类中的全部方法都是非抽象的,这个类不再是抽象类。

为了进行测试抽象类,我们在定义PersonTest类:

package abstractClasses;

public class PersonTest {
    public static void main(String[] args)
    {
        Person[] people = new Person[2];

        people[0] = new Employee("Harry Hacker",50000,1989,10,1);
        people[1] = new Student("Maria","compuer science");

        for(Person p: people)
        {
            System.out.println(p.getName()+", "+p.getDescription());
        }
    }
}

是否可以省略Person超类中的抽象方法,而仅在Employee和Student子类中定义了getDescription方法呢?如果是这样的话,就不能通过p调用getDescription方法了。编译器只允许调用在类中声明的方法。

猜你喜欢

转载自blog.csdn.net/leon_lavie/article/details/82849512
今日推荐