Sign in to follow this  
Degra

[Java] Calling template's static methods

Recommended Posts

Degra    212
I've got a class which looks something like this.. public class MyClass<theSubClass extends theSuperClass> { } theSuperClass and theSubClass are completely static. I need to be able to call a method in theSubClass (overridden from theSuperClass) from a function in MyClass, like this.... public void myFunction() { theSubClass.aStaticMethod(); } but I can't get it to work. Has anyone got any ideas? I'm fairly new to Java so it's probably a lack of understanding on my part. Degra

Share this post


Link to post
Share on other sites
Excors    715
Unlike C++ templates, Java generics only compile a single copy of your methods, so there's only a single implementation of myFunction (whereas C++ does one version per instantiated type).

When you call a static method of a class, there is no object involved, so you can't do run-time polymorphism (because that's based on looking at an object's vtable) - it's essentially the same as a plain function call in C.

So the call to aStaticMethod is jumping to a static method that it found at compile-time, and the code which does that call is only existing once (regardless of how many MyClass<T>s you use anywhere in the program), so it can only ever jump to one location, which means it can't possibly depend on the type of theSubClass. You can only use static methods when you tell the compiler precisely which class to look in.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this