I’m glad I found this forum.
I’m new to Java( beginner) and learning how to use setters, getters and constructor. I ran into an error and don’t know how to resolve it. Please help me in isolating this error.
I wrote two classes, first one is a simple java app called MyCalc that has 2 methods Add(), Multiply() and a setter setXY. MyCalc Class is instantiated using static void main().
2nd class “MyCalcTest” calls the first class. The standalone java app MyCalc runs fine without errors. But when I try to use setter ‘setXY’ from MycalcTest to set values for parameters, elipse doesn’t allow me to use setXY. Any reason why ?
Here is the code for both classes:
1)
public class MyCalc {
private double x, y;
//findout why it's throwing an error using setXY method from MyClacTest class
public void setXY(double x, double y) {
this.x = x;
this.y = y;
}
//this constructor with params works fine when called from MyCalcTest class
/*public MyCalc(double a, double b){
this.x = a;
this.y = b;
}*/
//getters
public double Add(){
return x+y;
}
public double Multiple(){
return (x * y);
}
public static void main(String[] args) {
//this works when called MyCalc with parameters
//MyCalc calc = new MyCalc(5, 5);
MyCalc calc = new MyCalc();
calc.setXY(5, 5);
System.out.println("Addition: " + calc.Add());
System.out.println("multiplication :" + calc.Multiple());
}
}
2)
public class MyCalcTest {
//this works when called MyCalc with parameters
//MyCalc calc = new MyCalc(5, 5);
MyCalc calc = new MyCalc();
//this doesn't workto set x,y why??
calc.setXY(5, 5);
}
Has to be inside a method/constructor/ initialization block.