虽然接触Java已经快一年了,也系统的学过Java语法,不过很多概念到现在都搞不清楚,现在决定重新把这些模糊的概念重新温习一遍,今天就现总结一下抽象类(abstract class)。
1、使用abstract类的动机:可以参考
Cay S. Horstmann,
Gary Cornel 写的书《Core Java™ 2 Volume I - Fundamentals, Seventh Edition 》(顺便罗嗦一下,该书是偶见过最好的Java入门书) “Classes, Superclasses, and Subclasses ”一节。2、如果一个类至少存在一个抽象方法(abstract method),则它自身必须声明成一个抽象类。但一个类可以被声明成一个抽象类即使它没有任何抽象方法。3、一个抽象类可以有数据域和非抽象方法(concrete data and concrete methods)。4、当一个子类继承某个抽象类时,它可以有两个选择:
(1) 部分实现或完全不实现父类的所有抽象方法,但此时子类必须声明为抽象类。
(2) 实现父类所有的抽象方法,此时之类不比声明为抽象类。
5、抽象类不能被实例化(be instantiated),但可以实例化非抽象子类(concrete subclass)。
可以声明抽象类变量,但该变量必须指向一个非抽象子类
6、摘自《Core Java 2》的一个例子:
1 /**
2 @version 1.01 2004-02-21
3 @author Cay Horstmann
4 */
5
6 import java.text.*;
7 import java.util.*;
8
9 public class PersonTest
10 {
11 public static void main(String[] args)
12 {
13 Person[] people = new Person[2];
14
15 // fill the people array with Student and Employee objects
16 people[0] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
17 people[1] = new Student("Maria Morris", "computer science");
18
19 // print out names and descriptions of all Person objects
20 for (Person p : people)
21 System.out.println(p.getName() + ", " + p.getDescription());
22 }
23 }
24
25 abstract class Person
26 {
27 public Person(String n)
28 {
29 name = n;
30 }
31
32 public abstract String getDescription();
33
34 public String getName()
35 {
36 return name;
37 }
38
39 private String name;
40 }
41
42 class Employee extends Person
43 {
44 public Employee(String n, double s,
45 int year, int month, int day)
46 {
47 super(n);
48 salary = s;
49 GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
50 hireDay = calendar.getTime();
51 }
52
53 public double getSalary()
54 {
55 return salary;
56 }
57
58 public Date getHireDay()
59 {
60 return hireDay;
61 }
62
63 public String getDescription()
64 {
65 return String.format("an employee with a salary of $%.2f", salary);
66 }
67
68 public void raiseSalary(double byPercent)
69 {
70 double raise = salary * byPercent / 100;
71 salary += raise;
72 }
73
74 private double salary;
75 private Date hireDay;
76 }
77
78
79 class Student extends Person
80 {
81 /**
82 @param n the student's name
83 @param m the student's major
84 */
85 public Student(String n, String m)
86 {
87 // pass n to superclass constructor
88 super(n);
89 major = m;
90 }
91
92 public String getDescription()
93 {
94 return "a student majoring in " + major;
95 }
96
97 private String major;
98 }
99
参考资料:
Core Java 2 Volume I - Fundamentals, Seventh Edition
by Cay S. Horstman, Gary Cornell
阅读(1583) | 评论(0) | 转发(0) |