Question

I understand the solution posted here Different return types of abstract method in java without casting

but, I don't think i can use generics because a few other classes contain "Content", that i don't want to decide which type of Content it is using at compile time.

public abstract class Content {
    public abstract Content getContent();
}

public class UrlContent : Content  {
    public String s;
    public getContent(){ return s;}

}

public class ImageContent : Content  {
    public Byte[] image;
    public getContent(){ return image;}
}
Was it helpful?

Solution

You could accomplish this using generics, and still maintain a non-generic interface that you can reference anywhere you don't need to know the return type, for example:

public interface IContent {
    object GetContent();
}

public abstract class Content<T> : IContent {
    public abstract T GetContent();
    object IContent.GetContent() 
    {
        return this.GetContent(); // Calls the generic GetContent method.
    }
}

public class UrlContent : Content<String>  {
    public String s;
    public override String GetContent() { return s; }
}

public class ImageContent : Content<Byte[]>  {
    public Byte[] image;
    public override Byte[] GetContent(){ return image; }
}

OTHER TIPS

Assuming the later implementations are meant to be public override Content getContent() methods...

You've declared your function as returning a Content object, then try to return String or a Byte[] from it. This won't work. If you want to be able to return any number of types, the simplest way is to return Object instead of Content, which will work fine for byte[] or string. It also serves as a warning to the calling code that the data type could be just about anything.

You could also use generics like you've referenced in that link and have the classes that don't return a specific type define themselves as public class StrangeContent : Content<object> so they can return multiple data types without forcing all the implementations to be loosely typed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top