❮ Previous Next ❯

Abstract Class:

We know that once a class is declared, we can declare any number of objects belonging to that class. When a method is written in the class, then it is available to all the objects of it's class. For example consider a class TestCube that contains a method cube() that calculates the cube value of a given number. If we create three objects to this class, all the three objects get the copy of this method. Let's see the program.

Example

class TestCube
{
void cube(int a)
{
System.out.println("cube="+(a*a*a));
}
}
class Test
{
public static void main(String args[])
{
TestCube ob1=new TestCube();
TestCube ob2=new TestCube();
TestCube ob3=new TestCube();
ob1.cube(2);
ob2.cube(3);
ob3.cube(4);
}
}

Output

cube=8
cube=27
cube=64

here in the above program we observed, that the requirement of all the objects is same that means to calculate the cube value.

But sometimes the requirement of the objects will be different and entirely dependent on the specific object only.

For example, let in the above program if the first object wants to calculate square value, the second object wants the square root value and the third object wants cube value by defining one calculate() method , then we can perform these tasks by implementing the concept of abstract class.

Let's see a program where an abstract class Simple having one abstract method which is implemented in various sub classes.

Example

import java.lang.*;
abstract class Calculation
{
abstract void calculate(int a);
}
class A extends Simple
{
void calculate(int a)
{
System.out.println("square="+(a*a));
}
}
class B extends Simple
{
void calculate(int a)
{
System.out.println("cube="+(a*a*a));
}
}
class C extends Simple
{
void calculate(int a)
{
System.out.println("square root="+Math.sqrt(a));
}
}
class AbstractDemo
{
public static void main(String args[])
{
A t1=new A();
B t2=new B();
C t3=new C();
t1.calculate(2);
t2.calculate(3);
t3.calculate(9);
}
}

Output

square=4
cube=27
square root=3.0

Points to remember:

❮ Previous Next ❯


  Tutorials

Contact Us

address Plot No-N6/530,2ND Floor
Nayapalli,Jayadev Vihar
      Bhubaneswar-751015
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

2017 Silan Technology. All Rights Reserved