Piyali Das - 2 months ago 9

Java Question

I have created the following java program. Its basic functionality is to perform addition, subtraction, multiplication, division and modular division on two numbers.

I have implemented the concept of object oriented programming but it is missing encapsulation.

How to introduce encapsulation in it? My code is:

`/*`

* To change this license header, choose License Headers in Project Properties.

* To change this template file, choose Tools | Templates

* and open the template in the editor.

*/

/**

*

* @author piyali

*/

public class Calculator {

/**

* @param args the command line arguments

*/

public static void main(String[] args) {

// TODO code application logic here

int x, y;

x = 13;

y = 5;

calculation add = new calculation();

calculation sub = new calculation();

calculation mul = new calculation();

calculation div = new calculation();

calculation mod = new calculation();

int addResult = add.addition(x, y);

int subResult = sub.subtraction(x, y);

int mulResult = mul.multiplication(x, y);

int divResult = mul.division(x, y);

int modResult = mod.modularDivision(x, y);

System.out.println("The addition of the numbers is " +addResult);

System.out.println("The subtraction of the two numbers is " +subResult);

System.out.println("The multiplication of the two numbers is " + mulResult);

System.out.println("The division of the two numbers is " +divResult);

System.out.println("The modular division of the two numbers is " + modResult);

}

}

class calculation {

int addition(int x, int y){

int z;

z = x + y;

return(z);

}

int subtraction(int x, int y){

int z;

z = x - y;

return(z);

}

int multiplication(int x, int y){

int z;

z = x * y;

return(z);

}

int division(int x, int y){

int z;

z = x / y;

return(z);

}

int modularDivision(int x, int y){

int z;

z = x % y;

return(z);

}

}

Answer

Well if you want true OOP and encapsulation, then create interface `Calculation`

which has a method `int calculate()`

.

```
public interface Calculation {
int calculate();
}
```

Now create classes which implements this interface such as `Addition`

or `Subtraction`

etc.

```
public class Addition implements Calculation {
private final int x;
private final int y;
public Addition(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int calculate(){
return x + y;
}
}
```

Main method

```
public static void main(String[] args) {
int x, y;
x = 13;
y = 5;
Calculation add = new Addition(x, y);
System.out.println(add.calculate());
}
```

Advantages of such design is that if you will want to add any extra mathematical operations such as root, percentage or even derivation, you will not need to modify any implementation of class. Just write extra class which implements `Calculation`

.

Source (Stackoverflow)

Comments