dr_yand
dr_yand

Reputation: 309

Java static function

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>().

Upvotes: 3

Views: 218

Answers (6)

roll1987
roll1987

Reputation: 183

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".

Upvotes: 0

Bohemian
Bohemian

Reputation: 424983

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.

Upvotes: 0

clumsy
clumsy

Reputation: 716

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

Upvotes: 0

pezetem
pezetem

Reputation: 2541

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?

Upvotes: 0

Zsolt S&#252;li
Zsolt S&#252;li

Reputation: 316

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

Read this: Overriding and Hiding Methods

Upvotes: 2

Marko Topolnik
Marko Topolnik

Reputation: 200148

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

Upvotes: 3

Related Questions