0

What is the need for a method which has a body or implementation inside the abstract class ?, does it need to be implemented by an extended class. Basically, what is the main use of the method body in abstract class? Like this code. (New to Java)

public abstract class Animal {

    protected int age;

    public void eat() {
        System.out.println("Animal is eating");
    }

    public abstract String getName();
}

class Swan extends Animal {

    public String getName() {
        return "Swan";
    }

I am tried implementing the method but doesn't work then what's the need of method body in abstract class?

  • 1
    Does this answer your question? [implementing abstract methods/classes in java](https://stackoverflow.com/questions/7665417/implementing-abstract-methods-classes-in-java) – fnymmm Jun 05 '23 at 10:54
  • This might be a dublicate to [this](https://stackoverflow.com/questions/7665417/implementing-abstract-methods-classes-in-java) question – fnymmm Jun 05 '23 at 10:54
  • The ability in an abstract class to allow some methods with bodies and other methods that must be implemented by subclasses is a feature that is needed and used by the [Template Method design pattern](https://en.wikipedia.org/wiki/Template_method_pattern). – k314159 Jun 05 '23 at 11:40

2 Answers2

2

Breaking up your example

   public void eat() {
       System.out.println("Animal is eating");
   }

implemented "normal" method, can be overriden by extending class

public abstract String getName();

abstract method - no body provided. This method MUST BE implemented (kind of overriden) in extending class

The reson for this is that you may have an general implementation of a problem in a base class that requires some details that must be provided by exending class. You can call abstract method in your abstract class which is not presented in your examplie, eg

public abstract String getName();

public void eat(){
   System.out.print(this.getName() + " is eating")
}

and the implementing class will be forced by the compiler to provide getName() implementation.

Antoniossss
  • 31,590
  • 6
  • 57
  • 99
0

An Abstract Class can have both abstract methods (having no bodies) and concrete methods (with bodies). The concrete methods in the abstract class provide default behavior that can be shared across all subclasses.

The eat() in Animal class is a concrete method. All subclasses of Animal will have this method and can use it without needing to have their own implementation of it.

Now, if a specific subclass (like Octopus) needs to eat in another way, it can override eat() method to provide its own behavior. If it doesn't override it, the default behavior from the Animal class is used.

The getName() is an abstract method and must be implemented by any class that extends Animal.

Payam Soudachi
  • 301
  • 3
  • 5