Recently I read that an abstract method essentially creates one marked for inheritance and that is block-less, awaiting subclass specialization. Well I ask this: What is the difference between creating an abstract method, allowing its inheritance, and making a subclass version, and having no corresponding superclass method, and one only defined by/in the subclass. By the principles of overriding, shouldn't a subclass object automatically use a subclass method, and if there is no corresponding superclass method, a subclass object would always use a subclass method. What is the purpose of creating an abstract method as opposed to just a standard method with no superclass counterpart.
My knowledge may be completely flawed and skewing my perception :-) any and all help will be greatly appreciated
It has to do with Polymorphism; the ability for one class to act like another.
Take the example of having an abstract class called Animal which is subclassed to Dog and Fish. If in the Animal class we have an abstract method move() then both Dog and Fish will be forced to implement the move() method.
public class Animal {
public abstract void move();
}
public class Dog extends Animal {
public void move() {
System.out.println("walk");
}
}
public class Fish extends Animal {
public void move() {
System.out.println("swim");
}
}
Furthermore, if we then have a helper method somewhere:
public static void moveTheAnimal(Animal a) {
a.move();
}
Then we know that whatever concrete class (subclass) is provided, a move() method is guaranteed to be defined.
If on the otherhand there was no abstract method move() in the Animal class, we would need a moveTheDog(Dog d) and moveTheFish(Fish f) etc. for each possible animal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With