is it compulsory for the abstract class to have at least one method as an abstract code example
Example 1: is it necessary for abstract class to have abstract method
No, abstract class can have zero abstract methods.
Example 2: write a program in which an abstract class is being defined containg an abstract method omputer(int a, int b) and a non abstract method as well
abstract class Sum{
public abstract int compute(int a, int b);
public void disp(){
System.out.println("Method of class Sum");
}
}
class Demo extends Sum{
public int compute(int a, int b){
return a+b;
}
public static void main(String args[]){
Sum obj = new Demo();
System.out.println(obj.compute(3, 7));
obj.disp();
}
}
Example 3: 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()}";)
}