简体   繁体   中英

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?

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM