Abstract Class Illustrated

  • 0
     An abstract class is the one having an abstract method in its definition. Abstract class puts a restriction that subclass must implement its own version of abstract methods. Programmer does not has the freedom to create object of an Abstract class. One can not declare abstract constructors or abstract static methods. One can not instantiate an Abstract class object with new operator. However, Java provides us the freedom to create an reference of Abstract class type. This reference can be used to store the reference of subclass object references.
    Here, is the program that clearly illustrates fallowing points.
package ClassIllustratiion;

abstract class A
{
 abstract void callme();
}
class B extends A
{
 void callme()
 {
  System.out.println("Abstract method defined in Class B");
 }
}
class C extends A
{
 void callme()
 {
  System.out.println("Abstract Method defind in Class C");
 }
}
class AbstractIllustration
{
 public static void main(String args[])
 {
  //Calling Callme() method with objects of class B and C
  B b = new B();
  b.callme();
  
  C c = new C();
  c.callme();
  
  //Calling Callme with Referace variable of class A
  A a;
  a = b;
  a.callme();
  
  a = c;
  a.callme();
 }
}
As you can see that class A is an abstract class. Classes B and C extend class A. This impose a restriction that they must either define their own version of callme() method or declare themselves abstract too. In line number 33, A reference of Class A is created. And it is used to store the reference of class B and C, and hence, can call callme() version of these methods via Dynamic Method Dispatch.
To compile the program
javac -d . AbstractIllustration.java
And tp run the program
java ClassIllustration.AbstractIllustration
here, is the sample output that I got.
Abstract method defined in Class B

Abstract Method defind in Class C

Abstract method defined in Class B

Abstract Method defind in Class C

No comments:

Post a Comment