'Should getters and setters used in pairs?
I am learning getters and setters in Java. I wrote the code below :
import java.util.*;
class test{
private int num1;
private int num2;
Scanner sc=new Scanner(System.in);
void mult(){
num1=sc.nextInt();
num2=sc.nextInt();
System.out.println("Multiply = "+(num1*num2));
}
public int getnum1(){
return num1;
}
public int getnum2(){
return num2;
}
}
class TestDemo{
void add(){
test ob=new test();
System.out.println("Num 1 = "+ob.getnum1());
System.out.println("Num 2 = "+ob.getnum2());
}
}
public class Main
{
public static void main(String[] args) {
System.out.println("Hello World");
test ob=new test();
ob.mult();
TestDemo ob2=new TestDemo();
ob2.add();
}
}
Inside the class TestDemo, I am trying to access the value of the variables num1 and num2 but in the output, I am getting 0 as shown here: output
Can anyone help me, how can I access the data inside the num1 and num2 inside TestDemo?
Solution 1:[1]
You should pass existing instance of test class to TestDemo instead of creating a new one. Like,
class TestDemo{
private test ob;
//set test instance through constructor or setter
TestDemo(test ob) {
this.ob=ob;
}
void add(){
System.out.println("Num 1 = "+ob.getnum1());
System.out.println("Num 2 = "+ob.getnum2());
}
}
public class Main
{
public static void main(String[] args) {
System.out.println("Hello World");
test ob=new test();
ob.mult();
TestDemo ob2=new TestDemo(ob);
ob2.add();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chetan Ahirrao |
