Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Video lesson

Working with Abstract Class in Java

In this lesson, you will learn

  • Background
  • Defining and Declaring Abstract Class
  • Features of an Abstract Class
  • Examples

 

Background

Sometimes, there are situations in which you want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method.

In that case, you will define that class as an Abstract class.

Note: An abstract class is exactly opposite to the final modifier. The final method can’t be overridden in their subclasses, but their subclasses must override the abstract method.

 

 

What is Abstract Class?

Here is the syntax to define the abstract method.

Syntax

abstract returntype method-name(parameter-list);

As you can see, no method body is present.

Important Point!

Any class that contains one or more abstract methods must also be declared as an abstract class..

 

Declaring an Abstract Class

Here’s the syntax to demonstrate abstract class in Java.

Syntax

public abstract class ClassName {
    // Field declarations
    int field1;
    String field2;

    // Constructor
    public ClassName(int field1, String field2) {
        this.field1 = field1;
        this.field2 = field2;
    }

    // Abstract method (does not have a body)
    public abstract void abstractMethod();

    // Concrete method (has a body)
    public void concreteMethod() {
        // Implementation code
        System.out.println("This is a concrete method.");
    }
}

 

Features of an Abstract Class

Here are the features of an abstract class in Java, explained in bullet points:

  • Cannot be Instantiated:
    • You cannot create objects of an abstract class directly using the new keyword.
  • Blueprint for Subclasses:
    • It serves as a base class or template for other classes (subclasses) to inherit from.
  • Abstract Methods:
    • Can contain abstract methods, which are methods declared with the abstract keyword and have no implementation (no method body).
    • Abstract methods must be overridden by concrete (non-abstract) subclasses.
  • Concrete Methods:
    • Can contain concrete (non-abstract) methods that have implementations.
    • These concrete methods provide default behavior that subclasses can inherit.
  • Constructors:
    • Can have constructors, which are called when a subclass object is created.
    • Used to initialize the state of the abstract class.
  • Instance Variables (Fields):
    • Can have instance variables (fields) that store data.
    • These fields are inherited by subclasses.
  • Inheritance:
    • Designed to be extended by other classes through inheritance using the extends keyword.
  • Abstraction:
    • Promotes abstraction by hiding implementation details and focusing on defining what a class does.
  • Partial Implementation:
    • Can provide partial implementations, leaving some methods abstract for subclasses to complete.
  • Interface Implementation:
    • Can implement interfaces, providing default implementations for some or all interface methods.
  • No Final Abstract Methods:
    • Abstract methods cannot be declared as final.
  • No Static Abstract Methods:
    • Abstract methods cannot be declared as static.

 

Example-1: Creating Abstract Class

package ch10;

//A Simple demonstration of abstract.
abstract class First {
	//abstract method without body
	abstract void callingme();
	
	// concrete methods with body
	void callingmetoo() {
		System.out.println("It is a concrete method.");
	}
}

class Second extends First {
	void callingme() {
		System.out.println("Subclass implementing callingme() of superclass");
	}
}

public class AbstractDemo {

	public static void main(String[] args) {
		Second objSecond=new Second();
		objSecond.callingme();
		objSecond.callingmetoo();
	}
}

Output

Subclass implementing callingme() of superclass
It is a concrete method.

 

Example 2: Abstract Class – Animal Hierarchy

package ch10;

abstract class Animal {
    // Field for the name of the animal
    private String name;

    // Constructor to set the name of the animal
    public Animal(String name) {
        this.name = name;
    }

    // Abstract method makeSound
    public abstract void makeSound();

    // Concrete method to get the name of the animal
    public String getName() {
        return name;
    }
    
    public void eat() {
    	System.out.println(getName()+" is eating food");
    }
}

class Dog extends Animal {
    public Dog(String name) {
        super(name); // Call the constructor of the Animal class
    }

    // Implementing the abstract method for Dog
    @Override
    public void makeSound() {
        System.out.println(getName() + " says: Bark");
    }
}

class Cat extends Animal {
    public Cat(String name) {
        super(name); // Call the constructor of the Animal class
    }

    // Implementing the abstract method for Cat
    @Override
    public void makeSound() {
        System.out.println(getName() + " says: Meow");
    }
}

public class AceesAnimal {

	public static void main(String[] args) {
		Animal dog = new Dog("Buddy");
        dog.makeSound(); // Output: Buddy says: Bark
        dog.eat(); //Output: Buddy is eating food

        Animal cat = new Cat("Whiskers");
        cat.makeSound(); // Output: Whiskers says: Meow
        cat.eat(); //Output: Buddy is eating food
	}
}

Output

Buddy says: Bark
Buddy is eating food
Whiskers says: Meow
Whiskers is eating food

Explanation

  • Abstract Class Animal: This class provides a template for animal objects with a common field name and a constructor to set this name. It declares an abstract method makeSound(), which forces subclasses to provide their own implementation of how the animal makes a sound.
  • Concrete Subclasses (Dog, Cat): These classes extend the Animal class and provide specific implementations of the makeSound() method. For example, Dog prints out “Bark” and Cat prints out “Meow”.
  • Usage: In the Main class, we instantiate Dog and Cat objects as Animal types and call the makeSound() method on them. This demonstrates polymorphism; the correct makeSound() method is called at runtime based on the actual object type.

 

Example-3: Shape Hierarchy

abstract class Shape {
    abstract double area();
    abstract double perimeter();

    void displayShapeType() {
        System.out.println("This is a shape.");
    }
}

class Circle extends Shape {
    double radius;

    Circle(double radius) {
        this.radius = radius;
    }

    @Override
    double area() {
        return Math.PI * radius * radius;
    }

    @Override
    double perimeter() {
        return 2 * Math.PI * radius;
    }
}

class Rectangle extends Shape {
    double width;
    double height;

    Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    @Override
    double area() {
        return width * height;
    }

    @Override
    double perimeter() {
        return 2 * (width + height);
    }
}

public class ShapeDemo {
    public static void main(String[] args) {
        // Shape shape = new Shape(); // Error: Cannot instantiate abstract class
        Circle circle = new Circle(5);
        Rectangle rectangle = new Rectangle(4, 6);

        System.out.println("Circle Area: " + circle.area());
        System.out.println("Rectangle Perimeter: " + rectangle.perimeter());
        circle.displayShapeType();
        rectangle.displayShapeType();
    }
}


Inside Area for Rectangle.
Area is 45.0
Inside Area for Triangle.
Area is 40.0
Area for Figure is undefined.
Area is 0.0

 

Quick Revision

Q: What is an abstract class in Java?

A: An abstract class is a class that cannot be instantiated. It serves as a blueprint for other classes, defining common properties and behaviors that subclasses must inherit. It can contain both abstract and concrete (non-abstract) methods.

Q: What is an abstract method in Java?

A: An abstract method is a method declared with the abstract keyword that has no implementation (no body). It only has a method signature. Abstract methods must be implemented by concrete (non-abstract) subclasses.

Q: How do I declare an abstract class?

A: Use the abstract keyword before the class keyword in the class declaration:

abstract class MyAbstractClass {
    // ...
}

Q: How do I declare an abstract method?

A: Use the abstract keyword before the return type of the method and end the method declaration with a semicolon:

abstract void myAbstractMethod();

Q: Can I create an object of an abstract class?

A: No, you cannot create an instance of an abstract class directly using the new keyword. Abstract classes are meant to be subclassed.

Q: Can an abstract class have a constructor?

A: Yes, abstract classes can have constructors. The constructor is called when a subclass object is created.

Q: Can an abstract class have non-abstract (concrete) methods?

A: Yes, abstract classes can contain both abstract and non-abstract methods. Non-abstract methods provide default implementations that subclasses can inherit.

Q: What happens if a subclass does not implement an abstract method?

A: If a subclass does not implement all abstract methods of its superclass, the subclass must also be declared as abstract.

Q: Can a non-abstract class extend an abstract class?

A: Yes, a non-abstract (concrete) class can extend an abstract class. However, the concrete subclass must provide implementations for all abstract methods of the superclass.

Q: What is the purpose of using abstract classes and abstract methods?

A: They promote abstraction and code reusability. They allow you to define a common interface and behavior for a group of related classes, while deferring the implementation details to subclasses.

Q: Can an abstract class implement interfaces?

A: Yes, abstract classes can implement interfaces. They can provide default implementations for some or all of the interface methods.

Q: Can an abstract method be final?

A: No, abstract methods cannot be final. final methods cannot be overridden, but abstract methods must be overridden by the subclasses.

Q: Can an abstract method be static?

A: No, abstract methods cannot be static. static methods belong to the class itself, while abstract methods are meant to be implemented by subclasses.

Q: When should I use an abstract class vs. an interface?

A:

  • Abstract classes: Use when you want to provide a common base implementation and share code among related classes. Use when you want to define a “is-a” relationship (e.g., a Car is a Vehicle).
  • Interfaces: Use when you want to define a contract that multiple unrelated classes can implement. Use when you want to define a “has-a” or “can-do” relationship (e.g., a Printer can print). Interfaces are also useful for multiple inheritance of type.

Q: Can an abstract class have instance variables (fields)?

A: Yes, abstract classes can have instance variables. These variables can be inherited by subclasses.

Q: How does the super() keyword related to abstract classes?

A: The super() keyword is used in a subclass constructor to call the constructor of its superclass (which can be an abstract class). This ensures that the superclass’s constructor is executed, initializing the superclass’s state.

 

Exercises for Practice

—————————————————————

Exercise 1: Vehicle Hierarchy

Objective: Create a Java program that models a simple vehicle hierarchy using abstract classes and inheritance. The hierarchy should differentiate vehicles by their method of movement.

Requirements:

  1. Define an abstract class Vehicle with:
    • A field for name and speed.
    • A constructor to initialize these fields.
    • An abstract method move() that describes how the vehicle moves.
    • A concrete method displayInfo() to print the vehicle’s name and speed.
  2. Create three concrete classes: Car, Boat, and Airplane, inheriting from Vehicle:
    • Car should override the move() method to indicate it moves by driving on roads.
    • Boat should override the move() method to indicate it moves by sailing on water.
    • Airplane should override the move() method to indicate it moves by flying in the air.
  3. In your main method, instantiate each of the three vehicle types, and call their move() and displayInfo() methods.

 

Exercise 2: University System

Objective: Implement a system to manage different types of members in a university using abstract classes and inheritance.

Requirements:

  1. Define an abstract class UniversityMember with:
    • Fields for name, age, and department.
    • A constructor to initialize these fields.
    • An abstract method getRole() that returns the member’s role in the university (e.g., “Student”, “Faculty”).
    • A concrete method printDetails() to output the member’s information.
  2. Create two concrete classes: Student and Faculty, inheriting from UniversityMember:
    • Student should have additional fields for studentID and major, and implement the getRole() method.
    • Faculty should have additional fields for facultyID and specialization, and implement the getRole() method.
  3. In the main method, create a list of UniversityMember objects that includes both Student and Faculty instances. Iterate over the list, calling printDetails() for each member.

 

Exercise 3: Credit Card System

Objective: Design a simple Java program to represent a credit card system using abstract classes and inheritance, focusing on different types of credit cards.

Requirements:

  1. Abstract Class CreditCard:
    • Fields: cardNumber, cardHolderName, and balance.
    • Constructor: Initializes the fields.
    • Abstract method: calculateInterest() that calculates the interest based on the balance and returns it.
    • Concrete method: displayCardInfo() to print the card number, holder’s name, and balance.
  2. Concrete Classes: Create subclasses RewardsCard, CashBackCard, and TravelCard inheriting from CreditCard:
    • Each subclass should implement the calculateInterest() method. The method should calculate interest differently based on the type of card:
      • RewardsCard might have a lower interest rate.
      • CashBackCard might offer cash back on the interest calculated.
      • TravelCard might have benefits related to travel expenses.
    • Optionally, add specific fields or methods to each card type (e.g., RewardsCard might have points).
  3. Main Class: In your main method:
    • Instantiate objects for each type of credit card.
    • Call the displayCardInfo() method and calculateInterest() on each object to show how each card calculates interest differently.

 

Exercise 4: Automobile Hierarchy

Objective: Build a Java program to model an automobile hierarchy using abstract classes and inheritance, emphasizing the different types of automobiles and their functionalities.

Requirements:

  1. Abstract Class Automobile:
    • Fields: make (the manufacturer), model, and year.
    • Constructor: Initializes the fields.
    • Abstract method: fuelType() which returns the type of fuel the automobile uses (e.g., gasoline, diesel, electric).
    • Concrete method: displayDetails() to print the make, model, and year of the automobile.
  2. Concrete Classes: Create subclasses Sedan, SUV, and ElectricCar inheriting from Automobile:
    • Sedan and SUV should implement the fuelType() method to return “gasoline” or “diesel”, respectively.
    • ElectricCar should implement the fuelType() method to return “electric”.
    • Each subclass may include additional fields or methods specific to its category (e.g., SUV might have a field for off-road capability).
  3. Main Class: In your main method:
    • Instantiate objects of each concrete class.
    • Call the displayDetails() and fuelType() methods on each object to demonstrate polymorphism.

 

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

5.0
5.0 out of 5 stars (based on 1 review)
Excellent100%
Very good0%
Average0%
Poor0%
Terrible0%

 

 

24/03/2025

clear and understandable

 

 

Submit a Review