Variable with same name in subclass and superclass

npkllr :

I'm currently working on some Findbugs issues of another persons project.
This is the issue I'm working on:

Correctness - Class defines field that masks a superclass field
This class defines a field with the same name as a visible instance field in a superclass. This is confusing, and may indicate an error if methods update or access one of the fields when they wanted the other.

There is the superclass OutputInterface and the subclass CoreOutputInterface which extends OutputInterface. Both of them define the variable className. CoreOutputInterface has some subclasses as well.

To fix the issue I would simply remove the className from the subclass (CoreOutputInterface) since it is already defined in the superclass.
The variable is never read or set with super.className or this.className, only with className, so in my opinion it should not lead to any problems.
Also the variable from the superclass is never referenced in the whole project (I checked it with the Eclipse reference function).

Can anyone confirm that this can not lead to a problem in any situation?

Thanks in advance for your help.


OutputInterface:

public abstract class OutputInterface {

    protected String className = null;

    ...
}

CoreOutputInterface:

public abstract class CoreOutputInterface extends OutputInterface {

    protected String className = null;

    ...

    public void getClassName() {
        return className;
    }

    public void setClassName(String newName) {
        className = newName;
    }

    ...
}
dim8 :

Yes, remove the declaration from the subclass. And provide/leave as they are in the example above a getter and, if needed, a setter. If the field's never used, it may simply have been overlooked, when 'CoreOutputInterface' was created, as the developer might have copy-pasted 'OutputInterface' and then edited it accordingly.

More theoretically, this is or could become, depending on the complexity and usage of the class, an example of broken Liskov substitution principle of the known SOLID OOP design principles. It states that superclass objects must be at all times replacable with their subclass counter-parts. Given there is a difference between both 'className' fields in use, a method could falsely rely on one or the other and lead to undefined behaviour, as stated in the report.

However, I am more confused, why a 'class' is called an Interface.

  • If it was really an interface, we wouldn't have had the problem in the first place, as interfaces allow only for constants. In that case getter and setter would have been sufficient.
  • If it is really a class, then one should drop the "Interface" from the name. Otherwise, the faulty name only hinders understanding and could lead to unexpected side-effects in future.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=103519&siteId=1