abstract classes and abstract methods code example
Example 1: abstract class in java
Sometimes we may come across a situation where we cannot provide
implementation to all the methods in a class. We want to leave the
implementation to a class that extends it. In such case we declare a class
as abstract.To make a class abstract we use key word abstract.
Any class that contains one or more abstract methods is declared as abstract.
If we don’t declare class as abstract which contains abstract methods we get
compile time error.
1)Abstract classes cannot be instantiated
2)An abstarct classes contains abstract method, concrete methods or both.
3)Any class which extends abstarct class must override all methods of abstract
class
4)An abstarct class can contain either 0 or more abstract method.
Example 2: java abstract class
// abstract class
abstract class Shape
{
// abstract method
abstract void sides();
}
class Triangle extends Shape
{
void sides()
{
System.out.println("Triangle shape has three sides.");
}
}
class Pentagon extends Shape
{
void sides()
{
System.out.println("Pentagon shape has five sides.");
}
public static void main(String[] args)
{
Triangle obj1 = new Triangle();
obj1.sides();
Pentagon obj2 = new Pentagon();
obj2.sides();
}
}
Example 3: is it necessary for abstract class to have abstract method
No, abstract class can have zero abstract methods.
Example 4: what is the need of abstract class
It is helpful if you need to make a generic function that can take a lot of class types as an argument. Eg:
abstract class Shape {
void area();
void perimeter();
}
class Rectangle extends Shape {
int width;
int height;
Rectangle(this.width, this.height);
void area() => this.width * this.height;
void perimeter() => 2*(this.width + this.height);
}
class Triangle extends Shape {
int side1;
int side2;
int side3;
Triangle(this.side1, this.side2, this.side3);
void area() => 0.5 * this.side1 * this.side2 * this.side3;
void perimeter() => this.side1 + this.side2 + this.side3;
}
void printGeometry(Shape shape) {
print("The area of this shape is ${shape.area()}";)
print("The perimeter of this shape is ${shape.perimeter()}";)
}