Create New Java Class Calculation Add Subtract

By | March 21, 2021

Java Program – Create a new class Calculation with add() and subtract methods to add two numbers and to subtract two numbers.

Design a New Java Calculation Class for addition and subtraction

Write down a Java Program to Design a Calculation Class with the following features:

  1. Define two instance variables num1, num2 of type double.
  2. Define two constructors – default constructor to initialize num1 and num2 with 0.0. One parameterized constructor to initialize num1, num2 with the given values passed by the user at the time of the object creation.
  3. Define 2 methods add() and subtract(). These methods will add num1, num2 and perform subtraction as well. The two methods will return the resultant value.
  4. Write down a class TestCalculation with main() method.
  5.  Create two objects obj1 and obj2 using default constructor and parameterized constructor by passing values(700.0,86.0).
  6. Call add() and subtract methods and show results.

 

Source Code for Program Create new Java Calculation Class

package testcalculation;

class Calculation
{
    private double num1;
    private double num2;
    
    Calculation()
    {
        num1=0.0;
        num2=0.0;
    }
    
    Calculation(double n1, double n2)
    {
        num1 = n1;
        num2 =n2;
    }
    
    double add()
    {
        return num1+num2;
    }
    
    double subtract()
    {
        return num1-num2;
    }
    
}
public class TestCalculation {

    
    public static void main(String[] args) {
  
        Calculation obj1 = new Calculation();
        Calculation obj2 = new Calculation(700.0,86.00);
        double ans1=obj1.add();
        double ans2=obj1.subtract();
        double ans3=obj2.add();
        double ans4=obj2.subtract();
        String s1="Object1 Results \n"+"Addition="+ans1+" Subtraction="+ans2;
        String s2="Object2 Results \n"+"Addition="+ans3+" Subtraction="+ans4;
        System.out.println(s1);
        System.out.println(s2);
    }
    
}

Output of a Sample Program Execution

Object1 Results 
Addition=0.0 Subtraction=0.0
Object2 Results 
Addition=786.0 Subtraction=614.0

You may also like to read a Java Program to define Rectangle class.

 122 total views,  1 views today

Leave a Reply

Your email address will not be published. Required fields are marked *