3

I have some classes.

class A{    
    static void v(){
        System.out.println("A");
    }
}

class A1 extends A{
    static void v(){
        System.out.println("A1");
    }
}

class B <T extends A>{
     void v(){
         T.v();
     }
}

Why following code outputs "A"?

B b = new B<A1>();
b.v();

I thought that the code should output "A1" because B<A1>().

Maroun
  • 94,125
  • 30
  • 188
  • 241
dr_yand
  • 171
  • 2
  • 11

6 Answers6

3

Your T.v() is a static method call and compiles into A.v() because T erases to A according to its upper type bound.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
2

You can't override static methods in Java, you can only hide them.

Read this: Overriding and Hiding Methods

Maroun
  • 94,125
  • 30
  • 188
  • 241
Zsolt Süli
  • 216
  • 2
  • 7
0

Shortly java does not support overwritting static methods:

here is a possible duplicate explaining better the case: Why doesn't Java allow overriding of static methods?

Community
  • 1
  • 1
pezetem
  • 2,503
  • 2
  • 20
  • 38
0

Static methods are not dispatched dynamically. The exact method to be called is resolved on compile time and it's A due to erasure.

aljipa
  • 716
  • 4
  • 6
0

The issue here is that calls to static methods are statically bound at compile time to the declared type of the variable. In this case, the compiler knows that T is an A.

It doesn't matter that the generic type of the local object is A1 - the binding is made inside B, where A is the only information the compiler has about the type.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

You didn't override the function v() for class T. Since T is a subclass of A, the effect of calling T.v() equals A.v() which outputs "A".

roll1987
  • 183
  • 1
  • 7