Home > Back-end >  call a non-static field of an abstract class in conflict with an interface's field
call a non-static field of an abstract class in conflict with an interface's field

Time:03-18

How to display the value of the "name" non-static field from the abstract class Confused("ConfusedValue") ? I tried 3 ways, but all have errors. I can display only the Confuslable's name value("ConfusableValue")

interface Confusable {
    String name = "ConfusableValue";

    String confuse();
}

abstract class Confused {
    String name = "ConfusedValue";

    abstract Object confuse();
}

public class Test extends Confused implements Confusable {
    public static void main(String[] args) {
        Test a = new Test();
        // --- OK
        System.out.println("Confusable.name: "   Confusable.name);
        // --- Errors
        System.out.println("name: "   name); // Error : The field name is ambiguous
        System.out.println("Confused.name: "   Confused.name); // Error : Cannot make a static reference to the non-static field Confused.name
        System.out.println("a.name: "   a.name); // Error : The field a.name is ambiguous
    }
}

CodePudding user response:

Field names are not inherited. They merely shadow each other. That's a concern for the compiler, but as far as the runtime is concerned, they both exist independently and just so happen to share a name.

So we just need to make the types look right to the compiler, and we can do that with explicit upcasts. These are upcasts (i.e. widening conversions), so they're safe and guaranteed to succeed.

System.out.println("The method confuse returns: "   ((Confused)a).name);
System.out.println("The method confuse returns: "   ((Confusable)a).name);
  • Related