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.
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); } }
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.
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); } }
square=4
cube=27
square root=3.0
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc