Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use an abstract class without abstract methods?

Tags:

java

I am now studying a java and I'm at the part of Abstract. I read sorta strange part to me that there is an abstract class which does not include any abstarct method.

Why do they use this kind of class?

like image 320
hongtaesuk Avatar asked Jul 28 '11 08:07

hongtaesuk


People also ask

Why do we need abstract class without abstract method?

An abstract class can extend only one class or one abstract class at a time. Declaring a class as abstract with no abstract methods means that we don't allow it to be instantiated on its own. An abstract class used in Java signifies that we can't create an object of the class directly.

Can we use abstract class without abstract method?

And yes, you can declare abstract class without defining an abstract method in it. Once you declare a class abstract it indicates that the class is incomplete and, you cannot instantiate it.

What is the point of using abstract classes?

The short answer: An abstract class allows you to create functionality that subclasses can implement or override. An interface only allows you to define functionality, not implement it. And whereas a class can extend only one abstract class, it can take advantage of multiple interfaces.

What is the use of abstract class without abstract method in C#?

Abstract Class: This is the way to achieve the abstraction in C#. An Abstract class is never intended to be instantiated directly. An abstract class can also be created without any abstract methods, We can mark a class abstract even if doesn't have any abstract method.


2 Answers

To prevent instantiation of that class and use it only as a base class. Child classes can use the general methods defined in the abstract class.

For example it doesn't make sense to create an instance of AbstractVehicle. But All vehicles can reuse a common registerMileage(int) method.

like image 112
Bozho Avatar answered Oct 06 '22 11:10

Bozho


A common reason to do this is to have the abstract class provide exploding implementations of the abstract methods as a convenience to subclasses who don't have to implement all the abstract methods, just those they want to - the remaining ones will still explode but it won't matter if those execution paths aren't exercised.

HttpServlet is an example of this pattern in action. It has default implementations for all methods that handle the different request types, but they all throw an exception. The subclass must override these if they want to do something meaningful. It's OK to leave some handler methods not overridden as long as they are never called.

like image 25
Bohemian Avatar answered Oct 06 '22 12:10

Bohemian