When a method in a child class has the same signature as a method in a parent class, it is assumed to be an override. However, that’s not the case
when:
- the parent class method is
static
and the child class method is not.
- the arguments or return types of the child method are in different packages than those of the parent method.
- the parent class method is
private
.
Typically, these things are done unintentionally; the private parent class method is overlooked, the static
keyword in the parent
declaration is overlooked, or the wrong class is imported in the child. But if the intent is truly for the child class method to be different, then
the method should be renamed to prevent confusion.
Noncompliant code example
// Parent.java
import computer.Pear;
public class Parent {
public void doSomething(Pear p) {
//,,,
}
public static void doSomethingElse() {
//...
}
}
// Child.java
import fruit.Pear;
public class Child extends Parent {
public void doSomething(Pear p) { // Noncompliant; this is not an override
// ...
}
public void doSomethingElse() { // Noncompliant; parent method is static
//...
}
}
Compliant solution
// Parent.java
import computer.Pear;
public class Parent {
public void doSomething(Pear p) {
//,,,
}
public static void doSomethingElse() {
//...
}
}
// Child.java
import computer.Pear; // import corrected
public class Child extends Parent {
public void doSomething(Pear p) { // true override (see import)
//,,,
}
public static void doSomethingElse() {
//...
}
}