Java Reference
In-Depth Information
Let's look at the simplest example of inheritance in Java. Let's start with an
Employee
class as listed in Listing 16-1.
Listing 16-1.
An Employee Class
// Employee.java
package com.jdojo.inheritance;
public class Employee {
private String name = "Unknown";
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
It is a simple class with a
private
instance variable
name
and two
public
methods,
setName()
and
getName()
.
The instance variable is used to store the name for an employee and the two methods are used to get and set the
name
instance variable. Note that there is no special code in the
Employee
class. It is one of the simplest classes you can
write in Java. It is easy to write and understand the following snippet of code that uses the
Employee
class:
Employee emp = new Employee();
emp.setName("John Jacobs");
String empName = emp.getName();
System.out.println("Employee Name: " + empName);
Employee Name: John Jacobs
Listing 16-2 contains the code for the
Manager
class, which inherits from the
Employee
class. Note the use of
the keyword
extends
to indicate that the
Employee
class is the superclass and the
Manager
class is the subclass. The
Manager
class does not contain any code, except the declaration. That is all you need in the
Manager
class for now.
Listing 16-2.
A Manager Class
// Manager.java
package com.jdojo.inheritance;
public class Manager extends Employee {
// No code is needed for now
}
Let's test the
Manager
class. Listing 16-3 contains the code.