Java: returning subclass in superclass method signature

后端 未结 3 758
没有蜡笔的小新
没有蜡笔的小新 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
    {
        @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
    {} // doStuff() will return an instance of ImplementationOne
    
    public class ImplementationTwo
    extends SuperClass
    {} // doStuff() will return an instance of ImplementationTwo
    

提交回复
热议问题