Abstract Class in Java
In this article, we will examine the concept of abstract classes using the Java programming language. We will begin by examining what abstract classes are used for and why we need them. In the end, we will examine the different properties of abstract classes with the help of programs to better understand their applications.
To grasp the concept more quickly and master it sooner, I recommend that you practice each code in the article, make some modifications, and experiment with the code to cover different scenarios. This will help you understand the concept better and be able to apply it in different situations.
The more you practice, the better you will understand and apply the concept. Experimenting with the code will help you see how it works in different situations and learn how to modify it to meet your needs.
What is an Abstract Class in Java?
An abstract class is a class declared with the keyword “abstract.” The abstract keyword is a Java modifier that can be used for classes and methods in Java but not for variables. An abstract class can have both abstract and non-abstract methods. Abstract methods do not have a method body.
Abstract classes are blueprints for other classes and cannot be instantiated themselves. Like regular classes, they are allowed to have constructors to initialize values. Abstract classes can also consist only of regular methods.
An abstract class can have a final method, but an abstract method cannot be final. A final method cannot be overridden, and a subclass must override an abstract method. If an abstract method were final, it would be impossible for the subclass to override it, which would cause an error.
A subclass cannot override a final method. An abstract method is a method that a subclass must override. If a method is both final and abstract, it would be impossible for a subclass to override it, which is why this is not allowed.
Abstract classes can have static methods; any class with at least one abstract method must be declared abstract. If a child class cannot implement all of the abstract methods of its parent class, then it should be declared abstract itself so that a subclass can provide implementations for the remaining abstract methods.
Before proceeding to further topics, let us take a look at an example program of an abstract class:
abstract class FirstCode {abstract void showdetails();} class FirstCodeEmployee extends FirstCode { void showdetails() { String name = "Gopi Kiran"; int age = 20; int ID = 21213; System.out.println("COMPANY: FirstCode"); System.out.println("NAME: "+name); System.out.println("AGE:"+age); System.out.println("ID: "+ID); } } class Main { public static void main(String args[]) { FirstCode emp1 = new FirstCodeEmployee(); emp1.showdetails(); } }
Output
COMPANY: FirstCode
NAME: Gopi Kiran
AGE: 20
ID: 21213
In the program shown above, the class “FirstCode” is an abstract class, with an abstract method “showdetails()”. The class “FirstCodeEmployee” is inherited from the class “FirstCode”, and the method “showdetails()” is overridden.
What are the properties of Java Abstract classes?
With the help of some codes, let us list down the different properties of abstract classes
1. Property
In Java, an abstract class cannot be instantiated. However, we can still have references to abstract class types. This is shown in the following Java program:
abstract class Animal {abstract void eat();} class Dog extends Animal { @Override void eat() {System.out.println("The dog is eating");} } public class FirstCode { public static void main(String[] args) { Animal animal = new Dog(); animal.eat(); } }
Output:
The dog is eating
In this program, the Animal class is an abstract class. We cannot create an instance of an abstract class, but we can create an instance of a subclass of an abstract class. In this case, the Dog class is a subclass of the Animal class. We can then make an example of the dog class and call it the eat() method.
2. Property
In Java, an abstract class can have constructors. When an instance of a subclass is created, the constructor of the abstract class is called.
This is demonstrated in the following program:
abstract class Animal { Animal() {System.out.println(“Animal constructor called”);} } class Dog extends Animal { Dog() {System.out.println(“Dog constructor called”); } } public class FirstCode { public static void main(String args) { Dog d = new Dog(); } }
Output:
Animal constructor called
Dog constructor called
3. Property
In Java, an abstract class can be created without any abstract methods. This allows us to create classes that cannot be instantiated but can only be inherited.
Here is an example:
abstract class Parent { void fun(){System.out.println("Method of the child class is called");} } class Child extends Parent {} class FirstCode { public static void main(String args[]) { Child obj = new Child(); obj.fun(); } }
Output:
Method of the child class is called
4. Property
Even though abstract classes cannot be instantiated, they can have final methods. Subclasses cannot override final methods, which is why they are sometimes used to enforce invariants.
Here is an example:
abstract class Parent { final void fun(){System.out.println("Method of parent class is called");} } class Child extends Parent {} class FirstCode { public static void main(String args[]) { Parent obj = new Child(); obj.fun(); } }
Output:
Method of parent class is called
5. Property
An abstract class in Java is a class that cannot be instantiated. This means that you cannot create an object of an abstract class. However, you can create objects of concrete classes inherited from an abstract class. Abstract classes are used to define a blueprint for other courses. They can contain methods that are declared but not implemented. The procedures defined in an abstract class must be implemented in the concrete classes that inherit from the abstract class.
Abstract classes are a valuable tool for code reuse because they allow you to define the behavior of a class without having to provide the implementation details. They allow you to define standard functionality that multiple classes can use.
abstract class FirstCode {} class Main { public static void main(String args[]) { FirstCode FC = new FirstCode(); } }
The program above will throw the error message below as we cannot instantiate objects from an abstract class.
6. Property
Abstract classes, like interfaces, can have static methods that can be called without creating an instance of the class. This can be useful for methods that do not need to access instance-specific data. For example, a static method might calculate a mathematical formula or print a message.
Here is an example:
abstract class FirstCode { static void print() { System.out.println("FistCode"); } } public class FC extends FirstCode { public static void main(String[] args) { FirstCode.print(); } }
Output:
FirstCode
7. Property
The abstract keyword can be used to declare both top-level (outer) and inner classes as abstract. When a class is declared abstract, it cannot be instantiated. This means that you cannot create an object of an abstract class. However, you can create objects of concrete classes inherited from an abstract class. Abstract classes often define a standard interface for multiple concrete classes.
Here is an example:
abstract class A { abstract class B {abstract void Method();} } class C extends A { class D extends B { void Method() {System.out.println("Abstract method invoked");} } } public class FirstCode { public static void main(String args[]) { C OuterClass = new C(); C.D InnerClass = OuterClass.new D(); InnerClass.Method(); } }
Output
Abstract method invoked
8. Property
A class with at least one abstract method must be declared abstract. Otherwise, a compile-time error will occur. If a class has at least one abstract method, its implementation is incomplete, and it is not recommended that an object be created from it. Therefore, the abstract keyword is used to restrict the creation of objects from such classes.
abstract class ParentClass {abstract void Method();} class ChildClass extends ParentClass {public void Method() {System.out.print("Abstract method Invoked");}} class FirstCode { public static void main(String[] args) { ChildClass obj = new ChildClass(); obj.Method(); } }
Output:
Abstract method invoked
9. Property
If a child class cannot implement all of its parent class’s abstract methods, it should also be declared abstract. This will allow a subclass of the child class to provide implementations for the remaining abstract methods.
abstract class ParentClass { abstract void method1(); abstract void method2(); abstract void method3(); } abstract class FirstChild extends ParentClass {public void method1() {System.out.println("Method 1 Invoked");}} class SecondChild extends FirstChild { public void method2() {System.out.println("Method 2 Invoked");} public void method3() {System.out.println("Method 3 Invoked");} } class FirstCode { public static void main(String[] args) { SecondChild s = new SecondChild(); s.method1(); s.method2(); s.method3(); } }
Output:
Method 1 Invoked
Method 2 Invoked
Method 3 Invoked
The need for Abstract Classes
1. Template programming
Template programming involves using abstract classes as a blueprint for classes that extend them. These abstract classes provide a predefined template for future specific classes, ensuring a consistent structure. This ensures a standardized template for the calculator app with variations in implementation for each device.
2. Loose coupling
Loose coupling is achieved when methods or classes are independent and less dependent on each other. Abstract classes contribute to loose coupling by allowing for easy maintenance, as changes to one class do not affect others. This approach also facilitates easier testing by dividing the project into small modules for unit testing.
3. Code reusability
The reusability of code is another benefit of using abstract classes. By declaring abstract methods in the class, developers can call them from various locations in the code, eliminating the need to write the same code repeatedly.
4. Abstraction
Abstraction in Java involves hiding the actual method implementation from end users and displaying only the method names (APIs). Abstract classes play a role in implementing abstraction by providing a framework with abstract methods.
5. Dynamic Method Resolution
Dynamic method resolution, a key feature of abstract classes, enables dynamic method dispatch or runtime polymorphism. When an overridden method is called, the Java Virtual Machine (JVM) dynamically resolves the version of the method to execute based on the type of object, contributing to the implementation of runtime polymorphism.
What are the advantages of implementing an abstract class in Java?
There are many advantages of implementing abstract classes into your Java programming; let us take a look at some of them:
Abstraction in Java helps prevent code duplication by encapsulating the implementation details of a class and exposing only the necessary functionality to the user.
Reusing code without worrying about the underlying implementation can help reduce the amount of code that needs to be written and maintained.
Additionally, abstraction can make code more readable and understandable by making it easier to see the overall structure of a program.
Abstract classes allow for code reuse by providing a blueprint from which other classes can inherit. This approach can speed up and simplify software development, as developers can focus on implementing the specific functionality of their classes rather than writing all of the code from scratch. Additionally, abstract classes can help enforce design patterns, which can improve the quality and consistency of code.
Encapsulation is a software design technique that hides a class’s internal details from its users, allowing changes to be made to the inner workings of code without impacting classes.
This allows the class’s users to interact with it without having to know how it works. This can be useful for making changes to a class’s inner workings without having to worry about breaking any code that uses the class.
What are the disadvantages of implementing an abstract class in Java?
With abstract classes, not everything is sunny and pretty; it has a couple of disadvantages. Let us take a look at some of them:
Abstraction in Java can be costly because it sometimes requires handling cases and situations that are not always necessary. For example, if you create an abstract class, you must provide implementations for all of its abstract methods, even if you don’t need all of those methods in your current code. This can make your code more complex and challenging to maintain. Additionally, abstraction can make it difficult to test your code, as you may not be able to test all the cases and situations your code could encounter.
However, abstraction can also be beneficial. It can help make your code more modular, reusable, and easier to understand and maintain. Ultimately, whether or not to use abstraction in Java is a trade-off between the benefits and costs of abstraction.
Object-relational mapping (ORM) is a technique that enables developers to map objects in an object-oriented programming language to data in a relational database. An ORM framework, such as Hibernate, can be used to accomplish this.
ORM frameworks abstract away the details of the database so that developers can focus on writing code that manipulates objects. This can make development much easier and faster and help improve applications’ performance.
Conclusion
In summary, abstract classes in Java are powerful tools for organizing and structuring code. They can define blueprints, enforce design patterns, and facilitate code reuse, making them essential for creating robust and scalable software solutions. While using abstraction has some trade-offs, the benefits of modularity, encapsulation, and maintainability make abstract classes an indispensable tool for Java developers.