Take the 2-minute tour ×

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;

    <T extends A> void g() {

    public static void main(String[] args) {
        Main m = new Main();
share|improve this question
"Why this happens?"What happens? You only told us what you expected to happen. –  stakx Jun 17 '12 at 8:34
interfaces in Java cannot have instance variables. They can only have constant values (i.e final instance variable) but it's considered a bad practice to put constant into an interface. –  Genzer Jun 17 '12 at 8:34
This code does not compile, is that your problem? –  Raging Scallion Jun 17 '12 at 8:35
@Cicada: actually, the code does compile. –  Genzer Jun 17 '12 at 8:43
interface should not contain non constat variables –  Subin Jun 17 '12 at 8:45
show 4 more comments

2 Answers

up vote 4 down vote accepted

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


it will print "BB".

You can find an answered similar question here

share|improve this answer
add comment

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.

share|improve this answer
"This is forbidden." No, it is not forbidden. It is just implicitly public, static, and final. –  newacct Jun 17 '12 at 21:47
add comment

Your Answer


