Peng
Peng

Reputation: 1491

Why bother using abstract method and overriding while we can always use a generic method in the superclass?

The following is a popular use case involving abstract method and overridding.

class Demo {
    public static void main(String[] args) {
        Parent a = new Child_A();
        Parent b = new Child_B();
        a.method();
        b.method();
    }
}

abstract class Parent {
    abstract void method();
}

class Child_A extends Parent {
    @override
    void method() {
        do the task for Child_A; 
    }
}

class Child_B extends Parent {
    @override
    void method() {
        do the task for Child_B; 
    }
}

It seems that we can always achieve the same thing by defining a generic method in the superclass, which uses the instanceof keyword to determine the subclass and performs the corresponding task for the subclass.

class Demo {
    public static void main(String[] args) {
        Parent a = new Child_A();
        Parent b = new Child_B();
        a.method();
        b.method();
    }
}

class Parent {
    void method() {
        if (this instanceof Child_A) {
            do the task for Child_A;
        }
        else if (this instanceof Child_B) {
            do the task for Child_B;
        }            
    }
}

class Child_A extends Parent {
}

class Child_B extends Parent {
}

Which code style is better and why?

Upvotes: 0

Views: 67

Answers (2)

Eldon Hipolito
Eldon Hipolito

Reputation: 724

If you do the latter, your subclasses becomes useless. They don't do anything. I'd like to think of it this way, the parent passed you the ability to do methodA in your own way. However in your case, the parent does everything, meaning you are dependent on your parent forever. Who would want that?

Well aside from that, when you create a new subtype, you'll have to edit also the parent(very absurd), think of what will happen 100 subtypes later. Give your subtypes the power to have their own individuality.

Upvotes: 0

user207421
user207421

Reputation: 310850

Because:

  • you don't want to have to modify the parent class every time you add another subclass
  • in some circumstances like a library API you may not even know all the subclasses
  • code that deals with a subclass should be in that subclass, not in the parent.

Upvotes: 1

Related Questions