Reputation: 415
This is a strange question but I was wondering if there was a way to "override" a parent class's static method in a subclass and call that subclass's static method from the parent class.
It would look something like this
public class parentFoo {
public static void <T extends parentFoo> printFoo () {
T.printFoo();
}
}
public class childFoo extends parentFoo {
public static void printFoo() {
System.out.println("Foo");
}
}
so you could do something like this in your code
//print out "Foo"
parentFoo.<childFoo>printFoo();
This isn't working for me but I was wondering if there is some way to make this possible. Right now I get a stack overflow because it only calls the parent class's printFoo method.
Upvotes: 0
Views: 3036
Reputation: 420951
There's no way to to call a static method based on a generic type parameter.
The answer to the question below provides a reasonable workaround.
Upvotes: 0
Reputation: 36703
You cannot override static methods. You can however define static methods of the same name. If you do that then you can specify which one is called from the class type
ChildFoo.printFoo(); // call child foo
ParentFoo.printFoo(); // call parent foo
ParentFoo foo1 = new ChildFoo();
foo1.printFoo(); // ParentFoo still called because of type of reference foo1 not its value
ChildFoo foo2 = new ChildFoo();
foo2.printFoo(); // ChildFoo called because of type of reference foo2 not its value
Upvotes: 2
Reputation: 258578
Replace
parentFoo.<childFoo>printFoo();
with
childFoo.printFoo();
Why would you need to override static
methods? (which isn't possible) What are you trying to accomplish?
A polymorphic call only makes sense for objects. Since statics aren't part of an object, but of a class, it doesn't.
Upvotes: 0