Given these classes:
class Father {
public Father getMe() {
return this;
}
}
class Child extends Father { .. }
I'm calling the public method of the Father class from the Child class:
Child c = new Child();
Child c1 = c.getMe();
So, this is not working, i have to use a cast to make it work :
Child c1 = (Child) c.getMe();
The question is: is there a better way to make it work without the cast? can be like this ?? :
public <T extends Father> T getMe() {
return this;
}
Thanks in advance.
You should override getMe method with return type Child at Child class. This feauture is called as covariant return, it comes with jdk1.5 ..
class Child extends Father{
public Child getMe() {
return this;
}
}
What about this solution?. It did not look elegant, you should cast to T at getThis method.. But there is no need to override getThis method at subclasses.. But unfortunately type safety is not enforced, one can define such a base object , Base<Child> baseChild = new Base<Child>();
Therefore I do not recommend this method..
class Base<T extends Base<T>> {
public T getThis() {
return (T) this;
}
}
class Child extends Base<Child>{
}
Child child = new Child();
child.getThis(); // return type is Child
Base base = new Base();
base.getThis(); // return type is base
This works :)))
Child c = new Child();
Child c2 = c; //same as c.getMe()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With