Aniketh
Aniketh

Reputation: 1

I have a java code ,cannot understand interface

Here is the code i have three interfaces

interface i1{ 
int x=1;
}
interface i2{ 
int x=2;
}
interface i3{ 
int x=3;
}
class A implements i1,i2,i3{
system.out.println(x); // It shows Field is ambgous
}

How to answer this or how to overcome this problem.

Upvotes: 0

Views: 126

Answers (6)

kTiwari
kTiwari

Reputation: 1508

*strong text*though answer to this question has been given by many.

but there is some detailed analysis.

  interface I1{ 
  int x=1;
  }
  interface I2{ 
  int x=2;
  }
  interface I3{ 
  int x=3;
  }
  class A implements I1,I2,I3{
  static{
   System.out.println(I1.x);
  }

  }

the integer x is a public final integer x. the compiler internally convert it as a final means treats it as the constant.

that's why when the user prints the value of x the compiler gives the ambiguous error for this.

for practically implementation of this please use -javap tool which is in jdk.

usage: javap I1

Upvotes: 0

adi
adi

Reputation: 1741

Don't do this. This is called Constant Interface Antipattern. Or just use the fully qualified names.

Upvotes: 0

CyanAngel
CyanAngel

Reputation: 1238

Interfaces are designed to demonstrate a class structure. If you must declare fields in multiple interfaces and use all those interfaces in one class, you should explicitly declare which interface you're using for that variable.

System.out.println(i3.x);

You can also use the extends keyword in your interfaces to decrease ambiguity by setting up inheritance.

interface i1{int x=1;}
interface i2 extends i1 {...}
interface i3 extends i2 {...}
class A implements i3{...}

Class A will have to implement all functions declared in i1,i2 and i3.

Upvotes: 0

Prasad Kharkar
Prasad Kharkar

Reputation: 13556

This is because same field is defined in all interfaces hence it doesn't know which field to use among these 3 .

  • You will have to specify interface name.
  • Code should be in some init block or method.
  • its System.out.println and not system

Also your names for types should start with capital leters

interface I1{ 
int x=1;
}
interface I2{ 
int x=2;
}
interface I3{ 
int x=3;
}
class A implements I1,I2,I3{
 static{
   System.out.println(I1.x);
}

}

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499740

How to answer this or how to overcome this problem.

Don't use fields in interfaces, or if you must use them, and they must have the same names, just fully qualify them:

System.out.println(i3.x);

Note that with import static, the "brevity" reason for importing interfaces containing constants is removed - interfaces should really only be implemented for genuine behavioural reasons. See Effective Java 2nd edition for more advice on this front.

Upvotes: 5

SpringLearner
SpringLearner

Reputation: 13844

In all the of the 3 interface variable x is there,so it shows ambiguous. Compiler confuses to print which x from i1 or i2 or i3

Upvotes: 0

Related Questions