How to rectify? — “both define getObjectCopy(), but with unrelated return types” — but it's *one* function

前端 未结 2 420
执笔经年
执笔经年 2021-01-26 05:08

I have the following interface heirarchy (with all non-relevant functions stripped out). I am getting this error when trying to compile it:

types ValidLineGettable

相关标签:
2条回答
  • 2021-01-26 05:54

    Assuming all the return values extend Copyable, have all versions of getObjectCopy() return Copyable. For example:

    public interface ValidateValue<O> extends Copyable
    {
         // Other functions...
    
         @Override
         Copyable getObjectCopy();
    }
    
    public Blammy implements ValidateValue<String>
    {
        // Other functions...
    
         @Override
        public Copyable getObjectCopy()
        {
            SomethingThatExtendsCopyable blammy = new SomethingThatExtendsCopyable();
    
            return (Copyable)blammy;
        }
    }
    

    Edit

    In your code above the error is caused by the fact that the "getObjectCopy" method has a different return value in the ValidateValue<String> and ValidLineGettable interfaces, but the calling signature is the same. In java, you do not get polymorphism by changing only the return value; this results in a compile error.

    If you change the return value to Copyable then the TextLineValidator no longer gains value by extending both of its parent interfaces. A simpler approach is to have one interface (Copyable) and multiple classes that implement that interface, each of which returns a Copyable value which may be an instance of a class that extends (or implements) Copyable.

    0 讨论(0)
  • 2021-01-26 05:54

    The Eclipse compiler compiles your code without errors. JavaC from JDK 7 (1.7.0_45) and JDK 8 (1.8.0-ea) also work.

    I think this is a bug in the JDK, most likely one related to bug #122881 (please note this one is fixed). I also found an issue in Google Protocol Buffer that points to another bug, but I can't find that one.

    You could compile it with Eclipse or JDK 7, or change the code so that it doesn't require this feature.

    0 讨论(0)
提交回复
热议问题