Friday, 25 November 2016

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.


PROGRAM
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();
  h.breath();
  h.eat();
  h.walk();
 } 
}
OUTPUT
C:\>javac Human.java
C:\>java Human
Hello from main
Living Thing breathing...
Living Thing eating...
Human walks...

No comments:

Post a Comment