Java: returning subclass in superclass method signature

后端 未结 3 750
没有蜡笔的小新
没有蜡笔的小新 2020-12-30 23:04

I\'m working on a problem where there are several implementations of Foo, accompanied by several FooBuilder\'s. While Foo\'s share sev

相关标签:
3条回答
  • 2020-12-30 23:34

    Having found this excellent answer I am now sharing it around.

    public class SuperClass<I extends SuperClass>
    {
        @SuppressWarnings( "unchecked" ) // If you're annoyed by Lint.
        public I doStuff( Object withThings )
        {
            // Do stuff with things.
            return (I)this ; // Will always cast to the subclass. Causes the Lint warning.
        }
    }
    
    public class ImplementationOne
    extends SuperClass<ImplementationOne>
    {} // doStuff() will return an instance of ImplementationOne
    
    public class ImplementationTwo
    extends SuperClass<ImplementationTwo>
    {} // doStuff() will return an instance of ImplementationTwo
    
    0 讨论(0)
  • 2020-12-30 23:37

    This is a good question and a real problem.

    The easiest way to deal with it in Java likely involves the use of generics, as mentioned in Jochen's answer.

    There's a good discussion of the issue and a reasonable solution in this blog entry on Using Inheritance with Fluent Interfaces, which combines generics with the definition of a getThis() method overriden in builder subclasses to solve the problem of always returning a builder of the correct class.

    0 讨论(0)
  • 2020-12-30 23:37

    Generics might be the way to go here.

    If you declare setA() something like this (pseudo-code)

    <T> T setA(int a)
    

    the compiler should be able to figure out the real types, and if it doesn't you can give hints in the code like

    obj.<RealFoo>setA(42)
    
    0 讨论(0)
提交回复
热议问题