24CS302 | OBJECT ORIENTED PROGRAMMING USING JAVA
UNIT III – INHERITANCE AND POLYMORPHISM
ABSTRACT CLASSES AND METHODS:
ABSTRACT CLASS:
An abstract class is a class declared using the keyword abstract.
It may contain abstract methods (methods without a body) as well as concrete
methods (methods with implementation).
KEY POINTS:
Abstract classes cannot be instantiated.
Abstract classes may contain:
Abstract methods (without implementation).
Non-abstract methods (with implementation).
Constructors, fields, static methods, etc.
If a class contains at least one abstract method, it must be declared as abstract.
Subclasses must implement all abstract methods of the abstract class, unless
the subclass is also declared abstract.
ABSTRACT METHODS:
Declared inside an abstract class.
Do not have a body — only method signature.
Must be implemented by the subclass.
Syntax:
abstract class ClassName
{
abstract void methodName(); // abstract method
}
EXAMPLE PROGRAMS:
abstract class Animal
{
abstract void sound(); // Abstract method (no body)
void sleep() // Concrete method
{
[Link]("Animal: Sleeping...");
}
}
class Dog extends Animal
{
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
24CS302 | OBJECT ORIENTED PROGRAMMING USING JAVA
void sound()
{
[Link]("Dog: Woof Woof!");
}
}
class Cat extends Animal
{
void sound()
{
[Link]("Cat: Meow Meow!");
}
}
public class TestAbstract
{
public static void main(String[] args)
{
// Animal a = new Animal(); // ❌ Not allowed
Dog d = new Dog();
[Link]();
[Link]();
Cat c = new Cat();
[Link]();
[Link]();
}
}
Output:
abstract class Shape
{
String color;
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
24CS302 | OBJECT ORIENTED PROGRAMMING USING JAVA
Shape(String color) // Constructor
{
[Link] = color;
}
abstract double area(); // Abstract method
void displayColor() // Concrete method
{
[Link]("Color: " + color);
}
}
class Circle extends Shape
{
double radius;
Circle(String color, double radius)
{
super(color);
[Link] = radius;
}
double area()
{
return [Link] * radius * radius;
} }
public class AbstractExample
{
public static void main(String[] args)
{
Shape s1 = new Circle("Red", 5);
[Link]();
[Link]("Area: " + [Link]());
Shape s2 = new Circle("Green", 10);
[Link]();
[Link]("Area: " + [Link]());
}
}
Output:
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY
24CS302 | OBJECT ORIENTED PROGRAMMING USING JAVA
ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY