Reputation: 3211
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();
}
Upvotes: 0
Views: 224
Reputation: 2991
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
Upvotes: 4
Reputation: 115328
There are too many problems in your code snippet.
f
is not terminated.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.
Upvotes: 0