Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Two classes with same name and same attibute in java

Imagine you have 2 package and there are public classes named – Test.

  • FirstPackage.Test
  • SecondPackage.Test

each of them have instance variable – x.

in first case – int x = 2;
in second case – int x = 3;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

i want to import FirstPackage.Test inside SecondPackage.Test and print x which has value 2.

My code:

package SecondPackage;
import FirstPackage.*;

public class Test {
   
   int x = 3;

   public static void main(String[] args){
     
      Test t = new Test();
      System.out.println(t.x);

   }


}

But output is 3. How can I print 2?

>Solution :

use full class name

so change this

Test t = new Test();

to

FirstPackage.Test t = new FirstPackage.Test();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading