0

Hi friends still I am not able to find the reason why we use abstract class .
for example:

public abstract class Test{

   abstract void show();

}

class Demo extends Test{

   public void show(){
      System.out.println("hi");
   }

   public static void main(String a[]) {

       Demo obj = new  Demo();
       show();
       obj.show();
   }

}

Instead of this I can directly use

class Demo {

    void show(){
       sop("hi");
    }

    public static void main(String a[]){
       Demo obj = new  Demo();
       obj.show();
    }
}

What is the use of abstract class here? How to use overriding concept without abstract class if it is possible?

Rohit Singh
  • 11,804
  • 4
  • 65
  • 66
Janarthanan Ramu
  • 1,057
  • 10
  • 15

2 Answers2

4

You should use an abstract class in case the same functionality is required in multiple classes. Since abstract classes can contain method-implementation, you can implement it once and inherit it in (multiple) other classes. This way you avoid code duplication and make it easier to maintain.

That said, in Java 8 you can create default methods in interfaces which is preferable since a class can implement multiple interfaces but can inherit only once. This approach also avoids other problems with inheritance.

Community
  • 1
  • 1
Nir Alfasi
  • 49,889
  • 11
  • 75
  • 119
  • 1
    Abstract classes - as do any class - allow adding additional fields/state; default methods do not. – user2864740 Jul 08 '15 at 18:48
  • @user2864740 true - but I never ran into a case where I had to use fields of an abstract class. Seems like an edge case to me. Good comment though - thanks! – Nir Alfasi Jul 08 '15 at 19:22
2

We use an abstract method when we may not have idea about how and what a method does but we are sure that a class includes a particular method, at that instance we could create an abstract method without any implementation code within it. And later on when we extend the method and get to know how the method must work, we can add implementation to it according to the current object or extending class.