[post-views]
In this lesson, you will learn
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.
abstract
keyword before the class keyword.
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.
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.");
}
}
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.
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.
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
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.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”.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.
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:
Vehicle
with:name
and speed
.move()
that describes how the vehicle moves.displayInfo()
to print the vehicle’s name and speed.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.main
method, instantiate each of the three vehicle types, and call their move()
and displayInfo()
methods.
Objective: Implement a system to manage different types of members in a university using abstract classes and inheritance.
Requirements:
UniversityMember
with:name
, age
, and department
.getRole()
that returns the member’s role in the university (e.g., “Student”, “Faculty”).printDetails()
to output the member’s information.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.main
method, create a list of UniversityMember
objects that includes both Student
and Faculty
instances. Iterate over the list, calling printDetails()
for each member.
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:
CreditCard
:cardNumber
, cardHolderName
, and balance
.calculateInterest()
that calculates the interest based on the balance and returns it.displayCardInfo()
to print the card number, holder’s name, and balance.RewardsCard
, CashBackCard
, and TravelCard
inheriting from CreditCard
: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.RewardsCard
might have points).main
method:displayCardInfo()
method and calculateInterest()
on each object to show how each card calculates interest differently.
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:
Automobile
:make
(the manufacturer), model
, and year
.fuelType()
which returns the type of fuel the automobile uses (e.g., gasoline, diesel, electric).displayDetails()
to print the make, model, and year of the automobile.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”.SUV
might have a field for off-road capability).main
method:displayDetails()
and fuelType()
methods on each object to demonstrate polymorphism.
There are no reviews yet. Be the first one to write one.
You must be logged in to submit a review.