wolfclique wolfclique - 2 months ago 13
Java Question

Can you have different return types of abstract methods?

Are you allowed to have different return types from an abstract method? Would this break polymorphism?

abstract class A {
public abstract void doSomething();

class B extends A{
public void doSomething(){
//do something specifically for B

class C extends A {
public int doSomething(){
//do something specifically for C
//that returns some int value

class D extends A {
public boolean doSomething(){
//do something specifically for D
//that returns some boolean value

I do not see a problem with class B as it's
method is
But is class C and D's
method legal as they have a return type? Would this break polymorphism? Also, do class B, C, and D's
method need


When you extend an abstract class, you're promising to implement the methods that you defined in the abstract class (remember: if you create a subclass from an abstract class and don't provide implementation for all of the abstract methods, then that subclass must still be declared abstract). The methods void doSomething() and int doSomething() aren't the same method, so you've broken the promise and haven't properly extended the abstract class.