Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Text lesson

Working with Abstract Classes in Java

[post-views]

 

 

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 will 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 the abstract method must be overridden by their subclasses.

 

 

Defining 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.

 

Note: Any class that contains one or more abstract methods must also be declared abstract.

 

Declaring 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?

1. Abstract classes define a common template for a group of related classes.

2. An abstract class is defined using the ‘abstract’ keyword.

3. Abstract class must contain at least one abstract method.

4. An abstract class cannot be instantiated, meaning you cannot create objects of an abstract class directly.

5. Abstract class can be used to create object references only, because Java’s approach to run-time polymorphism is implemented through the use of superclass references.

6. An abstract class can include abstract methods (without an implementation) and concrete methods (with an implementation).

7. Any subclass of an abstract class must either implement all of the abstract methods in the superclass or be declared abstract itself.

8. Abstract classes can have constructors, which can be called the constructors of their subclasses.

9. You cannot declare abstract constructors or abstract static methods.

10. An abstract class can have static methods that can be called without creating an instance of the class.

 

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.

 

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

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review

 

 

Layer 1
Login Categories