Home > Net >  Java rule that warns on hiding fields
Java rule that warns on hiding fields

Time:10-13

Java allows hiding fields

a field that has the same name as a field in the superclass hides the superclass's field

But it isn't consider a best practice

we don't recommend hiding fields as it makes code difficult to read.

Is there a rule that can warn on hiding fields in IDE or static tool?

I currently use VS code

We want to avoid issues as setting child field and getting parent field by mistake

public abstract class Parent {
   protected String a; 
   public abstract String test();
}
public class Child extends Parent {
   protected String a; 
    @Override
    public String test() {
        return null;
    }
}

CodePudding user response:

In Intellij IDEA:

Settings -> Editor -> Inspections -> Java -> Visibility -> Field name hides field in superclass

CodePudding user response:

Both Eclipse and IntelliJ allows you to configure a Warning or even an Error when you are hiding fields. Unfortunately neither runs on my tablet so that you have to lookup the details for yourself.

By the way, I am sure that NetBeans have something similar.


For Eclipse, you can look at "Preferences>Java>Compiler>Errors>Field declaration hides another field or variable."

  • Related