Syntax and Implementation
Abstract Class Declaration Syntax
In Java, an abstract class is declared using the abstract
keyword. Here's the basic syntax:
public abstract class ClassName {
// Class members and methods
}
Creating Abstract Methods
Abstract methods are declared without an implementation and must be defined in the subclass:
public abstract class Animal {
// Abstract method
public abstract void makeSound();
// Concrete method
public void breathe() {
System.out.println("Breathing...");
}
}
Implementing Abstract Classes
classDiagram
Animal <|-- Dog
Animal <|-- Cat
class Animal {
<
>
+abstract void makeSound()
}
class Dog {
+void makeSound()
}
class Cat {
+void makeSound()
}Example of implementing an abstract class:
public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Woof!");
}
}
public class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow!");
}
}
Abstract Class with Constructor
Abstract classes can have constructors that are called by subclass constructors:
public abstract class Shape {
protected String color;
// Constructor
public Shape(String color) {
this.color = color;
}
// Abstract method
public abstract double calculateArea();
}
public class Circle extends Shape {
private double radius;
public Circle(String color, double radius) {
super(color);
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
Key Implementation Rules
Rule |
Description |
Must Implement All Abstract Methods |
Subclasses must provide implementations for all abstract methods |
Can Have Concrete Methods |
Abstract classes can contain fully implemented methods |
Cannot Be Instantiated |
Direct object creation is not allowed |
Advanced Implementation Techniques
Multiple Abstract Method Implementation
public abstract class DatabaseConnector {
// Multiple abstract methods
public abstract void connect();
public abstract void disconnect();
public abstract void executeQuery();
}
Practical Considerations
- Use abstract classes when you have a base implementation
- Provide clear and meaningful abstract method signatures
- Ensure subclasses fully implement all abstract methods
LabEx recommends practicing these implementation patterns to master abstract class design in Java.