Why Abstract Class is used in Java?


A class is an abstract class if it contains at least one abstract method. It can contain other non-abstract methods as well. A class can be declared as abstract by using the abstract keyword. Also, an abstract class cannot be instantiated.

A program that demonstrates an abstract class in Java is given as follows:

Example

 Live Demo

abstract class Animal {
   abstract void sound();
}
class Cat extends Animal {
   void sound() {
      System.out.println("Cat Meows");
   }
}
class Dog extends Animal {
   void sound() {
      System.out.println("Dog Barks");
   }
}
class Cow extends Animal {
   void sound() {
      System.out.println("Cow Moos");
   }
}
public class Demo {
   public static void main(String[] args) {
      Animal a;
      a = new Cat();
      a.sound();
      a = new Dog();
      a.sound();
      a = new Cow();
      a.sound();
   }
}

Output

Cat Meows
Dog Barks
Cow Moos
raja
Published on 15-Feb-2019 14:47:24
Advertisements