Java Reference
In-Depth Information
So, how do you fix the
Manager2
class? There are many ways to fix it. Some of the ways you can fix the
Manager2
class are as follows.
You can add a no-args constructor to the
Employee2
class, like so:
public class Employee2 {
// A no-args constructor
public Employee2() {
}
/* All other code for class remains the same */
}
After adding a no-args constructor to the
Employee2
class, the code for the
Manager2
class will compile fine.
You can add a no-args constructor to the
Manager2
class and explicitly call the constructor of the
Employee2
class
with a
String
argument as
public class Manager2 extends Employee2 {
public Manager2() {
// Call constructor of Employee2 class explicitly
super("Unknown");
}
}
You can add a constructor to the
Manager2
class, which takes a
String
argument and pass the argument value
to the
Employee2
class constructor. This way, you can create a
Manager
by passing the name of the
Manager
as a
parameter to its constructor.
public class Manager2 extends Employee2 {
public Manager2(String name) {
// Call constructor of Employee2 class explicitly
super(name);
}
}
Normally, the third option is used where you would provide a way to create an object of the
Manager2
class
with manager's name. Note that
Manager2
class does not have access to the
name
instance variable of the
Employee2
class. Still, you can initialize the
name
instance variable in the
Employee2
class from the
Manager2
class using the
super
keyword and invoking the constructor of the
Employee2
class. Listing 16-24 has the complete code for the
Manager2
class that will compile. Listing 16-25 has code to test the
Manager2
class and its output shows that it works
as expected.
Listing 16-24.
A Manager2 Class That Has a Constructor That Accepts a String Argument. It Calls the Constructor of
the Employee2 Class Explicitly
// Manager2.java
package com.jdojo.inheritance;
public class Manager2 extends Employee2 {
public Manager2(String name) {
super(name);
}
}