Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ambiguous call from static context in Java

The main method tries to access var, but results in ambiguous call. Why? Instance variable var in Base1 isn't accessible (visible?) from static context anyway.

  class Base1 {
      int var;
  }

  interface Base2 {
      public static final int var = 0;
  }

  class Test extends Base1 implements Base2 { 
      public static void main(String args[]) {
          System.out.println("var:" + var); 
      }
  }
like image 440
user3613844 Avatar asked Jul 07 '14 14:07

user3613844


People also ask

What is ambiguous method call in Java?

This ambiguous method call error always comes with method overloading where compiler fails to find out which of the overloaded method should be used.

How do you handle ambiguity in Java?

Ambiguity errors occur when erasure causes two seemingly distinct generic declarations to resolve to the same erased type, causing a conflict. Here is an example that involves method overloading. In this case, Java uses the type difference to determine which overloaded method to call.

What is ambiguous in Java?

A grammar is said to be ambiguous if there exists more than one leftmost derivation or more than one rightmost derivative or more than one parse tree for the given input string.


1 Answers

The JLS rule for field access ambiguity is

If the identifier names several accessible (§6.6) member fields in type T, then the field access is ambiguous and a compile-time error occurs.

And on the subject of accessibility

A member (class, interface, field, or method) of a reference type, or a constructor of a class type, is accessible only if the type is accessible and the member or constructor is declared to permit access:

It doesn't make a distinction about whether the instance field access would cause a compile error in a static context.

Note that you could have had

public static void main(String args[]) {
    Test test = new Test();
    System.out.println("var:" + test.var); 
}

You'd still have the ambiguity.

like image 71
Sotirios Delimanolis Avatar answered Oct 01 '22 16:10

Sotirios Delimanolis