-3
abstract class B
{

}

public abstract class A 
{
  public abstract B createBInstance();
}

public class C extends A {
  @Override
  public D createBInstance() {
    return new D;
  }
}

where

public class D extends B 
{

} 

This give a compiler error saying attempting to use incompatible return type. Can't I do this. Any suggestions to avoid this error?

Filburt
  • 17,626
  • 12
  • 64
  • 115
Malinda
  • 336
  • 2
  • 12
  • 1
    Hmm. That looks like it should work. Can you provide a complete, minimal compilable code? – Thilo Jan 22 '16 at 07:28

1 Answers1

0

I have copied your code and run it with Java jdk8u45 and it works perfectly fine. In other words, when overriding a method it is possible to change the return type to a sublcass of the original return type.

See also: Can overridden methods differ in return type?

There is however a small error in your code, it should rather be:

public class C extends A {
   @Override
   public D createBInstance() {
       return new D(); //forgot parenthesis 
   }
}

Hope I could help, Best Y

Community
  • 1
  • 1
Yannik
  • 46
  • 8
  • Note: When I ran your code I defined all classes in seperate files. And above link states, with a Java version before 5.0 it is not possible to change the return type of a method. So which Java version are you using? – Yannik Jan 22 '16 at 07:50
  • The problem remains same. This is the The exactly same error given in this problem. http://stackoverflow.com/questions/28343916/java-android-studio-covariant-return-type-method-in-subclass-clashes-with – Malinda Jan 22 '16 at 10:02
  • java version is 1.8. There should be a minor error in the code. Thank you for you response. – Malinda Jan 22 '16 at 10:14
  • The link [yourlink](http://stackoverflow.com/questions/28343916/java-android-studio-covariant-return-type-method-in-subclass-clashes-with) you referred to, depicts a slightly different problem. In this problem the return type is not a subtype of the return type of the ovewrriden method. Can you provide the error and stack trace you are getting? – Yannik Jan 25 '16 at 09:35