Define a class Calculator ,which has method for basic functionality like add, sub, mul, divde. Define another class Calc which inherits Calculator and add some method to like sin, cosine . WAP to demonstrate the working of Inheritance.
Objective
Write a Java program to demonstrate Single Inheritance by extending a basic calculator.
Algorithm / Approach
- Create a base class
Calculatorwith basic arithmetic methods (add, sub, mul, div). - Create a derived class
Calcthat extendsCalculator. - Add advanced scientific methods (sin, cos) to the
Calcclass. - In
main, create aCalcobject and call both the basic (inherited) and advanced (new) methods.
Calculator.java
class Calculator {
void add(int a, int b) {
int c = a+b;
System.out.println("Add = "+c);
}
void sub(int a, int b) {
int c = a-b;
System.out.println("Sub = "+c);
}
void mul(int a, int b) {
int c = a*b;
System.out.println("Mul = "+c);
}
void div(int a, int b) {
float c = (float)a/b;
System.out.println("Div = "+c);
}
}
class Calc extends Calculator {
void getSin(int a) {
double x = Math.toRadians(a);
double res = Math.sin(x);
System.out.println("Result = "+res);
}
void getCos(int a) {
double x = Math.toRadians(a);
double res = Math.cos(x);
System.out.println("Result = "+res);
}
}
class Main {
public static void main(String[] a)
{
Calc c = new Calc();
c.add(20,10);
c.sub(20,10);
c.mul(20,10);
c.div(20,10);
c.getSin(90);
c.getCos(0);
}
}
Expected Output
Add = 30 Sub = 10 Mul = 200 Div = 2.0 Result = 1.0 Result = 1.0
Explanation of the Program
- Single inheritance involves one parent and one child class.
- This program perfectly illustrates the "Extensibility" benefit of inheritance. Imagine
Calculatoris an old, closed-source class that you cannot modify. - By extending it into
Calc, you can add new features (trigonometry) to it without ever touching or breaking the original code. The newCalcobject can do everything the old one did, plus more.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)