E
E
Evgeny Tarnov2019-06-28 21:24:14
Java
Evgeny Tarnov, 2019-06-28 21:24:14

Why is the changed variable not being read (getVal) from another class?

I cannot understand why the variable val changes depending on which method it is read in.
My code:

public class Main {

    public static void main(String[] args) {
  System.out.println("Start!");
  EditVal editVal = new EditVal();
  editVal.go();
    }
}

class Write{
    int val = 0;
    void setVal(int valGhanges){val = valGhanges;}
    int getVal(){return val;}
}

class EditVal{
    public void go() {
        Write write = new Write();
        write.setVal(1);// Здесь присвается переменной val значение 1 
        System.out.println("Read: " + write.getVal()); //Здесь выводит 1
        Read();
    }
    public void Read(){
        Write write = new Write();
        System.out.print(write.getVal()); // А почему здесь выводит ноль, Если в методе go() я присвоил значение 1?
    }
}

Help, I will be very grateful.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Tarnov, 2019-06-28
@etarnov

because Read creates a new object whose method you access.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question