Ich habe das folgende Java-Programm erstellt. Seine Grundfunktionalität besteht darin, Addition, Subtraktion, Multiplikation, Division und modulare Aufteilung auf zwei Zahlen durchzuführen.Wie führe ich die Kapselung in das folgende Java-Programm ein?
Ich habe das Konzept der objektorientierten Programmierung implementiert, aber es fehlt Kapselung.
Wie führe ich eine Verkapselung ein?
Mein Code ist:
/*
* 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);
}
}
Beachten Sie, dass die Kapselung den Schutz von Datenelementen, die als Felder bezeichnet werden, umfasst. Wenn Sie keine Felder haben, geben Sie nicht etwas frei, das eingekapselt werden muss. – Rogue
Hier kann ich leicht etwas tun wie sagen Berechnung b = neu Berechnung, b.z = 12, ich denke, wenn int z außerhalb der Funktion say addition() deklariert wäre, wäre die Kapselung praktisch –