Java Reference
In-Depth Information
Listing 16-23. Employee2 Class, Which Is a Modified Version of the Original Employee Class. It Has Added a
Constructor That Accepts a String Argument
// Employee2.java
package com.jdojo.inheritance;
public class Employee2 {
private String name = "Unknown";
public Employee2(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Let's call your new Manager class Manager2 , which inherits from the Employee2 class.
// Manager2.java
package com.jdojo.inheritance;
// Won't compile
public class Manager2 extends Employee2 {
// No code for now
}
The above code for the Manager2 class does not compile. It generates the following compiler error:
Error(4,23): constructor Employee2() not found in class com.jdojo.inheritance.Employee2
You have not added any constructor for the Manager2 class. Therefore, the compiler will add a no-args constructor
for it. It will also try to inject a super() call as the first statement inside the no-args constructor, which will call the
no-args constructor of the Employee2 class. However, the Employee2 class does not have a no-args constructor. This is the
reason that you get the above error. The code for the Manager2 class looks as follows, after it is modified by the compiler.
You may notice that that the super() call is invalid, because the Employee2 class does not have a no-args constructor.
// Code for Manager2 class after compiler injects a no-args constructor with a call to super()
package com.jdojo.inheritance;
// Won't compile
public class Manager2 extends Employee2 {
// Injected by the compiler
public Manager2() {
super(); // Calls the nonexistent no-args constructor of Employee2 class
}
}
 
Search WWH ::




Custom Search