Java Reference
In-Depth Information
Implementing Inheritance
Now that we have seen why inheritance is useful in OOP, let's look at how it is
implemented in Java. A class uses the extends keyword to inherit from another
class. The extends keyword appears after the class name when declaring the
class and is followed by the name of the class being extended.
For example, the following statement is used to declare that the Salary class
is a child of the Employee class:
public class Salary extends Employee
Similarly, the Hourly class can extend Employee with the statement:
public class Hourly extends Employee
The following Employee class will be used as the parent of Salary and
Hourly. Note that you do not add any special code to denote that Employee is
a parent class.
public class Employee
{
public String name;
public String address;
public int SSN;
public int number;
public void mailCheck()
{
System.out.println(“Mailing a check to “ + name
+ “ “ + address);
}
}
The following Salary class uses the extends keyword to denote Salary is a
child class of Employee.
public class Salary extends Employee
{
public float salary; //Annual salary
public float computePay()
{
System.out.println(“Computing salary pay for “ + name);
return salary/52;
}
}
Search WWH ::




Custom Search