简体   繁体   中英

Why this code give me compile Time error using Interface and how i can implement this code? Please Explain?

There are two interfaces and have common variable which is final.

interface abc {
    int a = 10;

    public void display();
}

interface xyz {
    int a = 20;

    public void display();
}

public class NewClass implements abc, xyz {
    public NewClass() {
        System.out.println(a);
    }

    public static void main(String[] args) {
        NewClass obj = new NewClass();
        obj.display();
    }

    @Override
    public void display() {
        System.out.println("hello");
    }
}

You are referring an unknown to the constructor variable a . You have to do:

System.out.println(xyz.a);

or

System.out.println(abc.a);

depending on which exact a you'd like to print.

This field a is ambigous, you can't have 2 same fields implemented. Also - interface variables are static and final by default. You don't even need to set them as static final.

Reference to a is ambiguous since its present in both the interfaces which NewClass implements.

To resolve this, you need to specify which variable you want to reference.

use System.out.println(abc.a) to refer the variable in abc interface or System.out.println(xyz.a) to refer a in xyz

This is the the diamond of death

Since Compiler is not smart enough to know which final variable you want to access untill you tell him which interface's final variable to use .

You have to specify like this

System.out.println(xyz.a);

or

System.out.println(abc.a);

a is "ambiguous". It could belong to either xyz or abc. That's why the compiler screams .

See, in this code :

public NewClass() {
    System.out.println(a); // a is "ambiguous". It could belong to either xyz or abc. That's why the compiler screams
}

Change your code to specify from which interface a must be used.like this

 public NewClass() {
        System.out.println(xyz.a);
    }

Thats a namespace conflict.

If the interfaces do simmilar things you should extend one from the other. If not, you should name the methods differently.

interface abc {
    public void display();
}

interface xyz extends abc {
    int a = 20;
}

Also, if the common field is not strictly needed for default methods in the interface you should not define them in the interface, but in the implementing class. Else give them a proper unique name.

Or access the variables / methods like this:

public NewClass() {
    System.out.println(xyz.a);
}

But in my optinion that is bad practice..

there is no any variable as 'a' in class NewClass if you want to use variable 'a' from interface abc or xyz ,,

public NewClass() {
    System.out.println(abc.a);
}

OR

public NewClass() {
    System.out.println(xyz.a);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM