Tuesday 27 December 2011

Abstract classes and Abstract methods

Abstract Class: Abstact class is a class which contains abstract methods as well as concrete(normal) methods we can not create an object for abstract classes.but we can create a reference for that


Abstract method: An Abstract method does not have method body it contains only  the method header

Example:
       
abstract class Myclass
{
    abstract void calculate(double x);
}
class Sub1 extends Myclass
{
    void calculate(double x)
    {
        System.out.println("square of "+x+" is "+(x*x));
    }
}
class Sub2 extends Myclass
{
    void calculate(double x)
    {
        System.out.println("squre root of "+x+" is "+Math.sqrt(x));
    }
}
class Sub3 extends Myclass
{
    void calculate(double x)
    {
        System.out.println("cube of "+x+" is "+(x*x*x));
    }
}
class Test
{
    public static void main(String[] args)
    {
        Sub1 obj1 = new Sub1();
        Sub2 obj2 = new Sub2();
        Sub3 obj3 = new Sub3();

      /* 2 ways to call calculate() method */

      /* 1.creating objects to subclasses of an abstarct class and call calculte()
           using that object reference*/

        //obj1.calculate(3);
        //obj2.calculate(4);
        //obj3.calculate(5);
       
      /*2.create a reference variable to Myclass once reference is created it can
          be used to refer to the objects of subclasses */
        Myclass ref;  //ref is the referance of myclass as this variable will not take any memory because of it is an abstract class ref
        ref = obj1; //ref is refering to obj1
        obj1.calculate(3);
        ref = obj2;//ref is refering to obj2
        obj2.calculate(4);
        ref = obj3;//ref is refering to obj3
        obj3.calculate(5);
    }
}

Output: Squre of 3.0 is 9.0
             Suare root of 4.0 is 2.0
             Cube of 5.0 is 125.0









No comments:

Post a Comment