简体   繁体   中英

Why doesn't polymorphism work in a generics method when using an interface?

I am trying to write a method that adapts to different types of interfaces using generics.

In this code I would have expected that the method f an g would print out "BB" instead of "interface A". Why did this happen?

interface A {
    String n="interface A";
}

interface B extends A {
    String n = "BB";
}

public class Main {
    <T extends A> void f() {
        T a = null;
        System.out.println(a.n);
    }

    <T extends A> void g() {
        System.out.println(T.n);    
    }

    public static void main(String[] args) {
        Main m = new Main();
        m.<B>f();
        m.<B>g();
    }

In your code, any classes or interfaces that extend/implement A will inherit the constant variable n .

The declaration of interface A actualy become like this:

interface A {
    public static final String n = "interface A"; //constant static varible
}

and you cannot override final variables in java.

If you write

System.out.println(B.n);

it will print "BB".

You can find an answered similar question here

There are too many problems in your code snippet.

  1. You tried to define field into interfaces. This is forbidden. Only methods or static fields are allowed in interface.
  2. Your method f is not terminated.
  3. It is not exactly clear what are you trying to do.

I'd suggest you to read about metamorphism first. Then try to implement some exercise without generics. Then read about generics, think what are you going to do and implement the second exercise with generics. Then if you still have questions post them here and we will be happy to help you.

Good luck.

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