Abstract class
Abstract Class and method in Java
In Java, an abstract class is a class that cannot be instantiated on its own. The keyword
‘abstract’ is used to declare a class or method as abstract.
Key Features:
• Cannot be Instantiated: Objects of abstract class cannot be created directly. A
subclass that extends the abstract class need to be created and has to be
instantiated.
• Abstract Methods: An abstract class can have abstract methods, which are
methods declared without a body. The subclass provides the implementation for
all such abstract methods. However, if it does not, then the subclass must also be
declared abstract.
Syntax of declaring a method as abstract:
abstract void myMethod();
A class should be declared abstract if it contains at least one abstract method.
• Non-Abstract Methods: An abstract class can also have regular methods with full
implementations, which can be inherited by subclasses.
• Constructors: Although an abstract class cannot be instantiated directly, it can
have constructors. These constructors are called when an object of a subclass is
created.
• Fields and Methods: Abstract classes can have fields and methods like any other
class, including static members, final methods, etc.
1. Program to demonstrate abstract class.
Source Code
[Link]
abstract class Product // Abstract class
{
private String name;
private double price;
public Product (String name, double price) { // Constructor
[Link] = name;
[Link] = price;
}
public abstract double calculateDiscount(); // Abstract method
// Regular methods
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public void displayInfo() {
[Link]("Product: " + name);
[Link]("Price: $" + price);
}
}
[Link]
class Electronics extends Product // Subclass for Electronics
{
public Electronics(String name, double price) {
super(name, price);
}
public double calculateDiscount() {
return getPrice() * 0.10; // 10% discount
}
}
[Link]
class Clothing extends Product // Subclass for Clothing
{
public Clothing(String name, double price) {
super(name, price);
}
public double calculateDiscount() {
return getPrice() * 0.15; // 15% discount
}
}
[Link]
public class AbstractExample // Main class
{
public static void main(String[] args)
{
Product laptop = new Electronics("Laptop", 1000);
Product jeans = new Clothing("Jeans", 50);
[Link]();
[Link]("Discount: " + [Link]());
[Link]();
[Link]("Discount: " + [Link]());
}
}