1

I have an abstract class with a method that i would like to return 'this' of the classes' subclasses. When i'm using the method i don't want it to return the object casted as MyClass and me have to recast it back to what it really is. Is there a pretty way of doing this with a generic?

abstract public class MyClass{

    public <aSubClassOfMyClass> doSomething(){

        return this;
    }
}
4

1 回答 1

2

您可以使用CRTP使类通用:

abstract public class MyClass<T extends MyClass<T>>{    
    public T doSomething(){    
        return this;
    }
}
于 2013-06-16T15:29:20.493 回答