Click here to Skip to main content
15,922,696 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
package com.gbr;

public class Hai {
public static int A=88;
}


package com.gbr;

public class Hello {
public static int A=99;
}


package org.sd;

import static com.gbr.Hello.*;
import static com.gbr.Hai.*;

class Test13 {
public static void main(String args[]){
	System.out.println(Hello.A);
        System.out.println(Hai.A);
}
}


Output: reference to A is ambiguous

How do I access the static variable A of both classes. What are other ways?

What I have tried:

I have executed the above codes.
Posted
Updated 22-Aug-17 16:30pm
v4
Comments
Richard MacCutchan 22-Aug-17 10:41am    
I just tried that and did not get any errors, and the final code prints the correct value.
Member 11735960 22-Aug-17 11:20am    
I am sorry. I have corrected the code.
Richard MacCutchan 22-Aug-17 11:30am    
Now you have different package names to the ones you are importing.
Richard MacCutchan 22-Aug-17 12:26pm    
Your problem really stems from the fact that you have two definitions of A. So unless you use the fully qualified name the compiler cannot be sure which one you are referring to.

Please read this document[^]


This one provides various examples on how you can declare

Improving Richard MacCutchan 's answer
package org.sd;

class Test13 {
public static void main(String args[]){
	System.out.println(com.gbr.Hello.A);
        System.out.println(com.gbr.Hai.A);
}
}

or
package org.sd;

import com.gbr.Hello;
import com.gbr.Hai;
class Test13 {
public static void main(String args[]){
	System.out.println(Hello.A);
        System.out.println(Hai.A);
}
}


or
package org.sd;

import static com.gbr.Hello.*;
import com.gbr.Hai;
class Test13 {
public static void main(String args[]){
	System.out.println(A);
        System.out.println(Hai.A);
}
}


or
package org.sd;

import static com.gbr.Hello.A;
import com.gbr.Hai;
class Test13 {
public static void main(String args[]){
	System.out.println(A);
        System.out.println(Hai.A);
}
}




Also read this to understand ambiguity[^]
 
Share this answer
 
v4
Comments
Member 11735960 22-Aug-17 22:45pm    
Thanks all for your answers. They were helpful. Thanks
Try:
Java
package org.sd;
 
import static com.gbr.Hello.*;
import static com.gbr.Hai.*;
 
class Test13 {
public static void main(String args[]){
	System.out.println(com.gbr.Hello.A);
        System.out.println(com.gbr.Hai.A);
}
}
 
Share this answer
 
Comments
Member 11735960 22-Aug-17 12:35pm    
Thanks. That works. Is this the only solution?
Mohibur Rashid 22-Aug-17 22:27pm    
I would not suggest that
Richard MacCutchan 23-Aug-17 3:08am    
Neither would I, but these days people seem to do what they want rather than what they should.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900