How do I introduce encapsulation in the following Java program? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this 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 do I 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);
}
}

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.

I don't think there's much to encapsulate here. This looks like it wants to be a basic math library, and since it has no data members, or helper functions, you can't do a whole lot here to encapsulate.
Since creating an instance of this class is a bit silly (see the Java Math library for example), make the methods static, and make the constructor private.
I guess not a form of encapsulation, but some design tips: You should make variables you aren't modifying final. You should also remove all unnecessary variables if you aren't using them. They aren't doing anything for readability, and they're just using extra blocks of memory (unless the JVM optimizes them out).
Improved code:
class calculation {
private calculation() {
throw new RuntimeException("Don't instantiate a math library!");
}
public static int addition(final int x, final int y){
return x + y;
}
public static int subtraction(final int x, final int y){
return x - y;
}
public static int multiplication(final int x, final int y){
return x * y;
}
public static int division(final int x, final int y){
return x / y;
}
public static int modularDivision(final int x, final int y){
return x % y;
}
}
By doing this, now you can call your calculation library with something like this:
int additionResult = calculation.addition(5, 5);
System.out.println(additionResult);

Use the concept of getter and setter.
class Calculator{
private int x, y, z;
void setValue(int a, int b){
x=a;
y=b;
}
int getValue(){
return z;
}
void addition(){
z=x+y;
}
void subtraction(){
z=x-y;
}
void multiplication(){
z=x*y;
}
void division(){
z=x/y;
}
void modDivision(){
z=x%y;
}
}
public class CalculatorTestDrive {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int num1, num2, result;
num1=13;
num2=5;
Calculator add = new Calculator();
Calculator sub = new Calculator();
Calculator mul = new Calculator();
Calculator div = new Calculator();
Calculator mod = new Calculator();
add.setValue(num1, num2);
add.addition();
result = add.getValue();
System.out.println("The addition of " + num1 + " and " + num2 + " is " +result);
sub.setValue(num1, num2);
sub.subtraction();
result = sub.getValue();
System.out.println("The subtraction of " + num1 + " and " + num2 + " is " +result);
mul.setValue(num1, num2);
mul.multiplication();
result = mul.getValue();
System.out.println("The multiplication of " + num1 + " and " + num2 + " is " +result);
div.setValue(num1, num2);
div.division();
result = div.getValue();
System.out.println("The division of " + num1 + " and " + num2 + " is " +result);
mod.setValue(num1, num2);
mod.modDivision();
result = mod.getValue();
System.out.println("The modular division of " + num1 + " and " + num2 + " is " +result);
}
}

Related

Making a Calculator using multiple classes

I've been trying to make a calculator with multiple classes, however I am not that experienced with classes. I've been having a few problems with it.
This is the user input section, doesn't seem to have any problems
import java.util.Scanner;
public class GetData
{
Scanner getdata = new Scanner(System.in);
public double intx;
public double inty;
public void getInt() {
System.out.print("Enter a number");
double intx = getdata.nextDouble();
}
public void getDouble() {
System.out.print("Enter a double");
double inty = getdata.nextDouble();
}
}
This is the operation section, the most problems are happening here, as said in the error there are missing error statements,
import java.util.Scanner;
public class MathOps {
Scanner mathops = new Scanner(System.in);
public double x;
public double y;
public double answer;
public double add(int x, int y) {
System.out.println("Adding " + x + "and " + y);
return x + y;
}
public double multiply(int x, int y) {
System.out.println("Multiplying " + x + "and " + y);
return x * y;
}
public double sub(int x, int y) {
System.out.println("Subtracting " + x + "and " + y);
if(x >= y) {
return x - y; }
if(y >= x) {
return y - x; }
}
public double divide() {
System.out.println("Dividing " + x + "and " + y);
if(x >= y) {
return x / y; }
if(y >= x) {
return y / x; }
}
}
----jGRASP exec: javac -g MathOps.java
MathOps.java:27: error: missing return statement
}
^
MathOps.java:35: error: missing return statement
}
^
2 errors
----jGRASP wedge2: exit code for process is 1. ----jGRASP: operation
complete.
This is were I'm putting it all together, also has problems
import java.util.Scanner;
public class L3Operations
{
int geti;
int getd;
public static void main(String[] args)
{
//instatnate
Scanner a = new Scanner(System.in);
int x1 = a.getInt();
}
}
As an aside, note that x >= y and y >= x will both be false if either x or y is Double.NaN, and you can enter NaN as a double value with the Scanner class (and also Infinity and -Infinity). So unless you check the values ahead of time to rule out NaN, you can't assume that at least one of those two conditions will be true.
You also can't assume that if x > y and y > x are false, then x == y, because for NaN all of those are false. And, if you have just assigned x = y, you can't assume that x == y, since if y was NaN that will be false.

What is wrong with my method for raising a complex number to a power

My method uses De Moivre's Theorem to raise a complex number a+bi to a power. However, I am not getting the right answers.
I double-checked all my math and it seems to be okay, so I'm thinking that I may have done my code wrong.
public class ComplexNumber {
//instance variables
private int real;
private int imaginary;
//constructors
public ComplexNumber(int a, int b) {
real = a;
imaginary = b;
//methods
public ComplexNumber pow(int x) {
int z = (int) Math.pow(this.getModulus(),x);
int T = (int) Math.atan(this.imaginary/this.real);
int a = (int) (z * Math.cos(x*T));
int b = (int) (z * Math.sin(x*T));
return new ComplexNumber(a, b);
}
public double getModulus() {
int z = (int) Math.sqrt(real*real + imaginary*imaginary);
return z;
}
For instance, for the complex number 3+4i raised to the 1st power, I am getting 5+0i.

Questions regarding alias in Java

public class Vector {
private int x, y, z;
public Vector(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public void add(Vector v) {
x += v.x;
y += v.y;
z += v.z;
}
public void silly(int x, int y, int z) {
this.x = ++x;
this.y = y + 1;
this.z += z;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getZ() {
return z;
}
#Override
public String toString() {
return "Vector, <x = " + x + ", y = " + y + ", z = " + z + ">";
}
public static void main(String[] args) {
Vector a = new Vector(1, 0, 0);
Vector b = new Vector(0, 1, 0);
Vector c = a;
int x = 1;
int y = 2;
int z = 3;
a.add(b);
b.add(b);
c.add(c);
c.silly(x, y, z);
System.out.println("a: " + a);
System.out.println("b: " + b);
System.out.println("c: " + c);
System.out.println("x: " + x + "\ty: " + y + "\tz: " + z);
}
}
I have obviously been unclear in my question, sorry about that. I got this as practice from my teacher and I am supposed to explain the output of the last 4 lines in the code. I have no idea why the output looks as it does. I'm not very good at alias and so on. Someone might be able to give me an explanation? Thanks.
Vector c = a;
means that you create reference which is linked to reference a and its object. You don't call a constructor there. You don't create any object there. Just new reference
The only question I can see is 'What is the relation between Vectors a and c?' So I'll answer that.
When you use the 'new' keyword you are creating a new object which is stored in the heap. So 'a' and 'b' are two separate objects when they have been instantiated. When you say:
Vector c = a;
You are not creating a new object in the heap, merely making a new reference to the same object. So now both 'a' and 'c' are referencing the same thing. If you change a, c will change, and vice versa.
When:
c.add(c);
Is called then the ints in c are simply being added to themselves.

Multi-Level inheritance not working

I'm working on a lab for school and I have it almost completed, but there's one part that I can't get to work. The inheritance works except when I get to Cube. For some reason, it won't calculate the Area or Volume (it just comes up with 0). I'm thinking it's a problem with the way I have the inheritance from Square to Cube. Help would be awesome!
package InheritanceTest;
import javax.swing.JOptionPane;
public class InheritanceTest {
public static void main(String[] args) {
String input = "";
Point point = new Point();
input = getinput("Set variable X");
point.setx(input);
input = getinput("Set variable Y");
point.sety(input);
System.out.println("Point, x = " + point.getx() + " y = " + point.gety());
Square square = new Square();
input = getinput("Set variable Side Length");
square.setSideLength(input);
System.out.println("Square, x = " + point.getx() + " y = " + point.gety()
+ " Area = " + square.getAreaOfSquare() + " Perimeter = "
+ square.getPerimeterOfSquare());
Cube cube = new Cube();
input = getinput("Set variable depth");
cube.setDepth(input);
System.out.println("cube, x = " + point.getx() + " y = " + point.gety()
+ " Depth = " + cube.getDepth() + " Area = " + cube.getAreaOfCube()
+ " Volume = " + cube.getVolumeOfCube());
}
private static String getinput(String string) {
String x = JOptionPane.showInputDialog(string);
return x;
}
}
package InheritanceTest;
public class Cube extends Square {
private int depth;
Cube() {
super();
depth = 0;
}
Cube(int x, int y, int sideLength, int d) {
super(x, y, sideLength);
this.depth = d;
}
public int getAreaOfCube() {
return (6 * sideLength * sideLength);
}
public int getVolumeOfCube() {
return (sideLength * sideLength * sideLength);
}
public String getDepth() {
return Integer.toString(depth);
}
public void setDepth(String i) {
depth = Integer.parseInt(i);
}
}
package InheritanceTest;
public class Point {
private int x;
private int y;
Point() {
x = 0;
y = 0;
}
Point(int x, int y) {
this.x = x;
this.y = y;
}
public String getx() {
return Integer.toString(x);
}
public String gety() {
return Integer.toString(y);
}
public void setx(String input) {
x = Integer.parseInt(input);
}
public void sety(String input) {
y = Integer.parseInt(input);
}
}
package InheritanceTest;
public class Square extends Point {
protected int sideLength;
Square() {
super();
sideLength = 0;
}
Square(int x, int y, int l) {
super(x, y);
this.sideLength = l;
}
public int getAreaOfSquare() {
return sideLength * sideLength;
}
public int getPerimeterOfSquare() {
return sideLength + sideLength;
}
public String getSideLength() {
return Integer.toString(sideLength);
}
public void setSideLength(String input) {
sideLength = Integer.parseInt(input);
}
}
When you create cube (new Cube()) you aren't setting the side length (or x and y) for the Square Object it extends.
Cube(){
// This is the constructor called.
super();
depth = 0;
}
Cube(int x, int y, int sideLength, int d){
super(x, y, sideLength);
this.depth = d;
}
You probably want extract the x,y and length values into variables and use "new Cube(x, y, length, depth)"
Something like the following
String x = getinput("Set variable X");
String y = getinput("Set variable Y");
String sideLength = getinput("Set variable Side Length");
String depth getinput("Set variable depth");
Cube cube = new Cube(x, y, sideLength, depth);
Look at how you are defining getVolumeOfCube(). You are calculating volume with sideLength, but you never set sideLength to any non-zero value. Change sideLength to depth and you will get the value you are looking for.

Return calculated value from enum

please my question are two and very simple
misinterpret enum as is
this idea missing some important abstraction in my code
code example, where oprt.calc(x, y) isn't compilable, with warning cannot find symbol
public enum Operation {
PLUS {
public double calc(double x, double y) {
return x + y;
}
},
MINUS {
public double calc(double x, double y) {
return x - y;
}
},
MULTILPLE {
public double calc(double x, double y) {
return x * y;
}
},
DIVIDED_BY {
public double calc(double x, double y) {
return x / y;
}
};
public static void main(String args[]) {
double x = 15.25;
double y = 24.50;
for (Operation oprt : Operation.values()) {
System.out.println(x + " " + oprt + " "
+ y + " = " + oprt.calc(x, y));
}
}
}
What you miss is abstract declaration of calc() method:
enum Operation {
PLUS {
public double calc(double x, double y) {
return x + y;
}
},
MINUS {
public double calc(double x, double y) {
return x - y;
}
},
MULTILPLE {
public double calc(double x, double y) {
return x * y;
}
},
DIVIDED_BY {
public double calc(double x, double y) {
return x / y;
}
};
**public abstract double calc(double x, double y);**
public static void main(String args[]) {
double x = 15.25;
double y = 24.50;
for (Operation oprt : Operation.values()) {
System.out.println(x + " " + oprt + " "
+ y + " = " + oprt.calc(x, y));
}
}
}
You need to declare an abstract method double calc(double x, double y) in the enum directly, and override it in every enum member.
The correct syntax to use enum methods is:
private enum Operation {
PLUS, MINUS, MULTILPLE, DIVIDED_BY;
public double calc(double x, double y) {
switch (this) {
case PLUS:
return x + y;
case MINUS:
return x - y;
case MULTILPLE:
return x * y;
case DIVIDED_BY:
return x / y;
}
return 0;
}
}
public static void main(String args[]) throws IOException {
double x = 15.25;
double y = 24.50;
for (Operation oprt : Operation.values()) {
System.out.println(x + " " + oprt + " " + y + " = "
+ oprt.calc(x, y));
}
}
You are overriding calc(), while you have no original calc() method. Either declare an abstract method:
public abstract double calc(double x, double y);
or declare a concrete method with a default implementation:
public double calc(double x, double y)
{
// ...
}
It doesn't compile because currently, the calc method only exists in each of the possible values of your enum - but it does not exist on the type Operation itself. That's why your compiler (and mine) doesn't accept it.
So, you need to define the method in the type. Maybe something like this:
public abstract double calc(double x, double y);
Your enum values (PLUS, MINUS, MULTIPLE and DIVIDED_BY each implement that method.
public double calc(double x, double y){}
is same as
private double calc(double x,double y){}
unless you add calc() method to the enum Operation.As per JLS:
Instance methods declared in these class bodies are may be invoked outside
the enclosing enum type only if they override accessible methods in
the enclosing enum type.
So basically , the type of oprt is Operation and as Operationdoesn't have any declaration for method called double calc(double x,double y), you cannot invoke the method using oprt. In short the methods defined in class bodies should be overridden methods, for them to be accessible outside.

Categories

Resources