Java Reference
In-Depth Information
Listing 16-3. Testing the Manager Class
// SimplestInheritanceTest.java
package com.jdojo.inheritance;
public class SimplestInheritanceTest {
public static void main(String[] args) {
// Create an object of the Manager class
Manager mgr = new Manager();
// Set the name of the manager
mgr.setName("Leslie Zanders");
// Get the name of the manager
String mgrName = mgr.getName();
// Display the manager name
System.out.println("Manager Name: " + mgrName);
}
}
Manager Name: Leslie Zanders
Even if you did not write any code for the Manager class, it works the same as the Employee class, because it
inherits from the Employee class. You create a manager object by using the Manager class's constructor.
Manager mgr = new Manager();
After the manager object is created, the code looks similar to the one you used for dealing with an Employee
object. You used the setName() and getName() methods with the manager object.
mgr.setName("Leslie Zanders");
String mgrName = mgr.getName();
Note that the Manager class does not declare the setName() and getName() methods. Neither does it declare the
name instance variable. However, it appears that all of them have been declared inside the Manager class, because
it uses the “ extends Employee ” clause in its declaration. When a class inherits from another class, it inherits its
superclass members (instance variables, methods, etc.). There are many rules that govern inheritance. I will discuss
those rules in details one-by-one later in this chapter.
Object Class is the Default Superclass
If a class does not specify a superclass using the keyword extends in its class declaration, it inherits from the
java.lang.Object class. For example, the following two class declarations for class P are the same:
// #1 - "extends Object" is implicitly added for class P
public class P {
// Code for class P goes here
}
 
Search WWH ::




Custom Search