Abstract – Java

Ebook: Core Java 2 Volumn 1

Abstract methods are an important concept in the Java programming language. You will encounter them most commonly inside interfaces.

Example 5-2. PersonTest.java
 1. import java.text.*;
 2. import java.util.*;
 3.
 4. public class PersonTest
 5. {
 6.    public static void main(String[] args)
 7.    {
 8.       Person[] people = new Person[2];
 9.
10.       // fill the people array with Student and Employee objects
11.       people[0] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
12.       people[1] = new Student("Maria Morris", "computer science");
13.
14.       // print out names and descriptions of all Person objects
15.       for (Person p : people)
16.          System.out.println(p.getName() + ", " + p.getDescription());
17.    }
18. }
19.
20. abstract class Person
21. {
22.    public Person(String n)
23.    {
24.       name = n;
25.    }
26.
27.    public abstract String getDescription();
28.
29.    public String getName()
30.    {
31.       return name;
32.    }
33.
34.    private String name;
35. }
36.
37. class Employee extends Person
38. {
39.    public Employee(String n, double s,
40.       int year, int month, int day)
41.    {
42.       super(n);
43.       salary = s;
44.       GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
45.       hireDay = calendar.getTime();
46.    }
47.
48.    public double getSalary()
49.    {
50.       return salary;
51.    }
52.
53.    public Date getHireDay()
54.    {
55.       return hireDay;
56.    }
57.
58.    public String getDescription()
59.    {
60.       return String.format("an employee with a salary of $%.2f", salary);
61.    }
62.
63.    public void raiseSalary(double byPercent)
64.    {
65.       double raise = salary * byPercent / 100;
66.       salary += raise;
67.    }
68.
69.    private double salary;
70.    private Date hireDay;
71. }
72.
73.
74. class Student extends Person
75. {
76.    /**
77.       @param n the student's name
78.       @param m the student's major
79.    */
80.    public Student(String n, String m)
81.    {
82.       // pass n to superclass constructor
83.       super(n);
84.       major = m;
85.    }
86.
87.    public String getDescription()
88.    {
89.       return "a student majoring in " + major;
90.    }
91.
92.    private String major;
93. }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s