![]() |
VOOZH | about |
An abstract method in Java is a method that is declared without a body and is marked using the abstract keyword. It specifies what a method should do but leaves the implementation to subclasses. Abstract methods are used to achieve abstraction by defining a common contract that derived classes must follow.
7 -1
Explanation: In this example, the abstract class ArithmeticOperation declares an abstract method printInfo(). The Add and Sub classes extend the abstract class and provide their own implementations of printInfo(). When the method is called using the abstract class reference, the corresponding subclass implementation executes, demonstrating runtime polymorphism.
abstract returnType methodName(parameterList);
Example 1: Abstract Class with Abstract and Concrete Methods
B's implementation of m1. This is a concrete method.
Explanation: In this example, class A contains both an abstract method m1() and a concrete method m2(). Class B extends A and implements the abstract method m1(). The object of class B can access both the implemented abstract method and the inherited concrete method.
Note: Abstract classes cannot be instantiated, but their references can point to subclass objects, enabling runtime polymorphism.
Example 2: Abstract class with an abstract method.
Area of rectangle=156 Area of square=144 Area of circle=15.197601
Explanation: In this example, the abstract class Geometry defines three abstract methods for calculating rectangle, square, and circle areas. The Easy class implements all these methods and provides the actual area calculation logic. This ensures a common structure while allowing specific implementations.
All the methods of an interface are public abstract by default because of which we can declare abstract methods inside an interface.
200 6000
Explanation: In this example, the interface Multiply declares abstract methods for multiplication operations. The Demo class implements the interface and provides method implementations. This demonstrates how interfaces use abstract methods to define behavior contracts.
As we have mentioned that we cannot use final with abstract Method as a modifier but we can create a Final method in abstract class.
Area = 156 Perimeter = 50
Explanation: In this example, the abstract class Geometry contains an abstract method rectangleArea() and a final concrete method rectanglePerimeter(). The abstract method must be implemented by subclasses, while the final method cannot be overridden, ensuring consistent behavior.