Я создал следующую программу Java. Его основная функциональность - выполнять сложение, вычитание, умножение, деление и модульное деление на два числа.Как я могу представить инкапсуляцию в следующей программе Java?
Я реализовал концепцию объектно-ориентированного программирования, но отсутствует инкапсуляция.
Как мне ввести инкапсуляцию?
Мой код:
/*
* 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);
}
}
Обратите внимание, что инкапсуляция включает в себя защиту элементов данных или полей. Если у вас нет полей, вы не раскрываете то, что должно быть инкапсулировано. – Rogue
Здесь я могу легко сделать что-то вроде say Расчет b = new Calculation, b.z = 12, я думаю, если int z был объявлен вне функции say addition(), инкапсуляция пригодится –