user3613844
user3613844

Reputation: 273

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); 
      }
  }

Upvotes: 17

Views: 886

Answers (4)

Anirudh
Anirudh

Reputation: 2326

The static and non static contexts do not rule on how variables are permitted to be accessed

The access modifiers are the ones which actually rule this...

change the access modifier for var in the Base1 to private and the ambiguity disappears, though this might not be the way you want it to shape up but access modfiers actually dictate the reference to instance variables rather than the static no static contexts.

class Base1 {
    private int var;
    //static int var=5;
}

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

class ambiguousNonStaticCall extends Base1 implements Base2 { 
    public static void main(String args[]) {
        System.out.println("var:" + var); 
    }
}

The above code compiles fine.

Upvotes: 1

Darshan Lila
Darshan Lila

Reputation: 5868

Inititally at step one compiler will look for variable var in the class which you extend and the interface you implement. Since it finds a variable at both places in step two, it shows ambiguity.

Upvotes: 1

Jens Baitinger
Jens Baitinger

Reputation: 2365

To make it unambiguous put the interface name as qualifying prefix:

class Test extends Base1 implements Base2 { 

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

Upvotes: 3

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279910

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.

Upvotes: 17

Related Questions