0

I tried to enter assertTrue into code and found that i need to import junit lib.

In this code,

import static org.junit.Assert.assertTrue;
//import org.junit.Assert;   with this didnt worked

public class Person implements Serializable {
       // some code there

        assertTrue(p2.getAge() == p.getAge());
        assertTrue(p2.getName().equals(p.getName()));
}

So i tried with import org.junit.Assert; but that asserTrue didnt worked then I tried with import static org.junit.Assert.assertTrue; and then it works. I need explanation why need static ?

R.Nish
  • 73
  • 2
  • 15
  • you don't "have to", you can also just call the static method without a static import – Stultuske Oct 04 '19 at 06:37
  • no need, imports are optional, just use `org.junit.Assert.assertTrue(p2.getAge() == p.getAge());`, that is, the fully qualified name of the class/method... clearly it looks *better*, more readable, using the import – user85421 Oct 04 '19 at 06:45

1 Answers1

3

With the static keyword you can use the methods without qualifying the class the method belongs to. See this relevant part in the documentation:

The static import construct allows unqualified access to static members without inheriting from the type containing the static members. Instead, the program imports the members [...]

Static import

Elias
  • 1,532
  • 8
  • 19