-3

My question is why do we use abstract class when we can use a normal class? We can define the class methods with the empty body, which is the only difference with the abstract class is that its methods do not have a body, but the normal class methods have a body that is empty, which with this normal class we can also use polymorphism facilities. In this case, what is the need for abstract class?

class NormalClass{
 
void m1(){
 }

}
//instead of:

 abstract class AC{
 void m1();

 }
amz
  • 34
  • 5
  • 1
    So we create an abstract class that can be extended by many other classes, and contain all the common logic, and force behavior (abstract methods) – Stultuske Mar 27 '21 at 17:36
  • yup you force the "user" (another subclass if your class) to implement this specific method themselfs. – IntoVoid Mar 27 '21 at 17:37
  • What did your search turn up? I am sure that reasons and arguments are given in many places. – Ole V.V. Mar 27 '21 at 17:44
  • 2
    "We can define the class methods with the empty body," true, but that way subclass isn't *forced* to specify behavior of those methods. With abstract methods compiler is forcing subclass to provide that implementation, even if subclass author will decide to make it empty. For instance you can have `Animal` abstract class and force each subclass to implement `makeSound()` method according to subclass they represent (like `class Cat extends Animal` can implement `public void makeSound(){sout("mew");}`). – Pshemo Mar 27 '21 at 17:44
  • 1
    Having an abstract class as superclass for just one concrete class often does not make a lot of sense. Having an abstract with abstract methods as superclass for several concrete classes has at least two advantages: (1) you don’t accidentally instantiate the abstract superclass (2) you don’t accidentally forget to implement the methods in the concrete classes (same as what @IntoVoid and Pshemo said). – Ole V.V. Mar 27 '21 at 17:46
  • There’s also the readability and clarity of code aspect: An empty method body will tell the reader that this method is supposed to do nothing. Which will usually be very misleading. – Ole V.V. Mar 27 '21 at 17:48

1 Answers1

0

The main difference is that the abstract class will force all the inherited classes to override those methods. The normal class will simply pass on the empty methods, and if the inheriting class misses defining the inherited methods, then they will stay empty.