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?
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.
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.
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.
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.
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.
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.
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