forked from ronreiter/interactive-tutorials
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Abstract Classes
91 lines (82 loc) · 2.35 KB
/
Abstract Classes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
Abstraction means the ability to make a class abstract in OOP.
An abstract class is one that cannot be instantiated.
All other functionality of the class still exists, and its fields, methods, and constructors are all accessed
in the same manner. But cannot create an instance of the abstract class.
Example:
/* File name : Employee.java */
public abstract class Employee
{
private String name;
private String address;
private int number;
public Employee(String name, String address, int number)
{
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public double computePay()
{
System.out.println("Inside Employee computePay");
return 0.0;
}
public void mailCheck()
{
System.out.println("Mailing a check to " + this.name
+ " " + this.address);
}
public String getName()
{
return name;
}
public String getAddress()
{
return address;
}
public void setAddress(String newAddress)
{
address = newAddress;
}
public int getNumber()
{
return number;
}
}
The class is now abstract, but it still has three fields, few methods, and one constructor.
This means the class can't directlt creat object of its type. But can help an inherited class to create object.
Thus the class's functionality totallt abstracted from outside.
/* File name : Salary.java */
public class Salary extends Employee
{
private double salary; //Annual salary
public Salary(String name, String address, int number, double salary)
{
super(name, address, number);
setSalary(salary);
}
public void mailCheck()
{
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to " + getName() // call the Employee.getname()
+ " with salary " + salary);
}
public double getSalary()
{
return salary;
}
public void setSalary(double newSalary)
{
if(newSalary >= 0.0)
{
salary = newSalary;
}
}
public double computePay()
{
System.out.println("Computing salary pay for " + getName());
return salary/52;
}
}
Here, we cannot instantiate a new Employee, but if we instantiate a new Salary object,
the Salary object will inherit the three fields and seven methods from Employee.