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.
The answer is 'Yes'. We can have two or more static methods with the same name, but differences in input parameters.
Static import is a feature introduced in the Java programming language that allows members (fields and methods) which have been scoped within their container class as public static , to be used in Java code without specifying the class in which the field has been defined.
This is Expert Verified Answer The static import feature of Java 5 facilitate the java programmer to access any static member of a class directly. There is no need to qualify it by the class name.
A static method can call only other static methods; it cannot call a non-static method. A static method can be called directly from the class, without having to create an instance of the class.
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:
A static-import-on-demand declaration never causes any other declaration to be shadowed.
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.
Overloading and overwriteing works in an inheritance tree. But a static import doesn't build a inheritance.
If you want to use the assertEquals of junit in your own assertEquals method you must qualify it with the className e.g. Assert.assertEquals.
Use a nonstatic import of org.junit.Assert.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With