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

前端 未结 2 424
执笔经年
执笔经年 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 extends Copyable
    {
         // Other functions...
    
         @Override
         Copyable getObjectCopy();
    }
    
    public Blammy implements ValidateValue
    {
        // 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 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.

提交回复
热议问题