Wednesday, 5 June 2019

Abstract class in java can’t be instantiated

Because that would contravene their whole purpose.

Abstract classes, by design, are not complete or functional. They are meant to serve as a base from which complete classes can be built, by aggregating the common members and methods that they all will need into an abstract base class, and then allowing the inheriting classes to fill out the necessary
details.

Take a database connection. Alright, you have an abstract class, DatabaseConnection. All database connections are going to need some things, such as URL/IP address, port, login information, etc. That can all go in the abstract class. But there will be certain details for particular types of databases that are specific to those. That will be defined in MySQLConnection, or OracleConnection, or whatever have you. But there's no point in having each one of those reimplement what's needed for all of them.

Instantiating a "DatabaseConnection" class makes no sense, as it doesn't have what's needed to actually connect to any databases. It's like trying to use the frame of a house to live in. That frame plan might be the same between dozens of houses, but the details of the walls and interior are different, and before the house can be useful, you have to actually implement those too. "Abstract" tells future developers "This isn't complete, it's just a starting point and you need to finish it for it to be useful."

(This is deliberately simplified for use as an example of abstract classes, and setting up database connection objects is quite a bit more complex than such an example.)

Read More:

What is Abstraction in Java? Abstract Class or Interface
important Interface and abstract class interview questions

No comments:

Post a Comment

Spring Boot @ConfigurationProperties and Properties File

 In this tutorial, you will learn to use @ConfigurationProperties to map properties files to POJO classes in Spring Boot application. Let’s ...