I have a Junit4 test case which statically imports the org.junit.Assert.assertEquals method(s).
import static org.junit.Assert.assertEquals;
In this class I have created a utility method for asserting some complex internal classes which do not implement equals (and also have a hard time implementing it).
private void assertEquals(MyObj o1, MyObj o2)
{
assertEquals(o1.getSomething(), o2.getSomething());
assertEquals(o1.getSomethingElse(), o2.getSomethingElse());
...
}
I expected the code to behave as if I am “overloading” the assertEquals method(s) that I’m importing, but it looks like my private non-static method is hiding the statically imported methods. I also tried turning my method to be public and static (all permutations) but with no success – I had to rename it.
Any reason why it behaves this way? I couldn’t find any reference to this behavior in the documentation.
What you observed is calling Shadowing. When two types in java have the same simple name, one of them will shadow the other. the shadowed type then can’t be used by it’s simple name.
The most common type of shadowing is a parameter to hide a field. usually result in setter code to look like
setMyInt(int myInt) {this.myInt = myInt; }Now let’s read the relevant documentation:
This indicate a static import on demand always comes last, so any type with the same simple name as a import on demand declaration will always shadow (hide) the static import.