Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java inheritance

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.

like image 603
Seby Avatar asked Mar 24 '11 14:03

Seby


2 Answers

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
like image 128
Gursel Koca Avatar answered Sep 25 '22 17:09

Gursel Koca


This works :)))

Child c = new Child();
Child c2 = c; //same as c.getMe()
like image 38
rodion Avatar answered Sep 22 '22 17:09

rodion