Program for Abstract class and Abstract method

An abstract class is a class that cannot be instantiated. When a method is declared as "abstract" in a class it must be overridden by the subclass of the super classes which contain that method. An abstract method does not have body. Body of an abstract method will be defined by subclass. To declare an abstract method use the following form:
abstract  return-type  <method-name> (parameter-list);

Any class that contains one or more abstract methods must also be declared as abstract. That is, an abstract class cannot be directly instantiated with the new operator.
abstract class <class-name> {

 // abstract method
 abstract return-type <method-name>( );
 // concrete or non-abstract method
 return-type <method-name>( );

In below program, LivingThing is an abstract class which contains one abstract method called walk( ) and two concrete methods breath( ), eat( ). In subclass Human you must override the abstract method walk( ) and make implementation in it. Note that you cannot create an object of abstract class.
abstract class LivingThing {

 public void breath() {   //Concrete method
  System.out.println("Living Thing breathing...");

 public void eat() {
  System.out.println("Living Thing eating...");
 * Abstract method walk()
 * We want this method to be implemented by a
 * Concrete class.
 public abstract void walk();

public class Human extends LivingThing
 public void walk() {
  System.out.println("Human walks...");
 public static void main(String[] args) {
  System.out.println("Hello from main");
  Human h = new Human();
C:\>java Human
Hello from main
Living Thing breathing...
Living Thing eating...
Human walks...

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to input age from user and throw user-defined exception if entered age is negative