Advertisement
Google Ad Slot: content-top
Java Abstract keyword
The abstract keyword in Java is used to define abstract classes and methods. It plays a key role in achieving abstraction in object-oriented programming, allowing you to define methods without implementation and enforce implementation by subclasses.
Abstract Class:
An abstract class is a class declared with the abstract keyword. It:
- Can include abstract methods (methods without implementation) and concrete methods (methods with implementation).
- Cannot be instantiated (you cannot create objects of an abstract class).
- Serves as a blueprint for subclasses.
Syntax:
abstract class ClassName {
// Abstract method (no implementation)
abstract void abstractMethod();
// Concrete method (with implementation)
void concreteMethod() {
System.out.println("This is a concrete method.");
}
}
Example
abstract class Animal {
// Abstract method
abstract void sound();
// Concrete method
void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks.");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound(); // Calls the overridden method
myDog.eat(); // Calls the inherited concrete method
}
}
Abstract Methods:
An abstract method:
- Is declared using the
abstractkeyword. - Does not have a body (implementation).
- Must be implemented by any concrete subclass of the abstract class.
Example
abstract class Shape {
abstract void draw(); // Abstract method
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing a Circle.");
}
}
class Rectangle extends Shape {
void draw() {
System.out.println("Drawing a Rectangle.");
}
}
public class Main {
public static void main(String[] args) {
Shape shape1 = new Circle();
shape1.draw();
Shape shape2 = new Rectangle();
shape2.draw();
}
}