0
public static void main(String[] args) {
        WeatherData subject =new WeatherData();
        new ShowEstadistics(subject);
} 


public class WeatherData implements Subject {

    ArrayList<Observer> observers;

    public WeatherData() {
        observers = new ArrayList();
    }

    @Override
    public void registerObserver(Observer o) {
        observers.add(o);
    }
}



public class ShowEstadistics implements Observer{

WeatherData weatherdata;

public ShowEstadistics(WeatherData subject) {
     this.weatherdata=subject;

     this.weatherdata.registerObserver(this);
        
    }

I dont know how the observer is registered in subject in this part:

public ShowEstadistics(WeatherData subject) {
         this.weatherdata=subject;
    
         this.weatherdata.registerObserver(this);
            
        } 

because I apply the registerObserver method to weatherdata but for some reason, it is registered in subject too. I don't know why.

Someone explain me, please.

1 Answers1

-1

Suppose that you have this code scenario:

Integer x=new Integer(4);
Integer y=new Integer(5);
y=x;
x=new Integer(2);

What do you think the value of y is in this case? Is it an Integer Object containing 5? The answer is Integer Object Containing 2.

When we say that Integer x=new Integer(4), we mean that x is pointing at an address in the memory which has an object containing a value of 4. Similarly for y, y is pointing at an address in memory which has an object containing a value of 5. Writing then y=x indicates that we remove the pointer at address having object containing 5 and point it at what x is pointing at which is currently object of value 5. Address of object containing 5 doesn't have any variable pointing at it anymore and hence, you can't call or modify its value. After changing the object of address pointed by x and y to an object with a value of 2 with x=new Integer(2), calling any of these variables would return the same object (because they have same reference).

Now this is a basic example based on Integer object type, but can be applied to any more complex objects.

  • 1
    Unfortunately, you've choosen a primitive data type to demonstrate the behaviour of reference types. Therefore your example is plain wrong; the value of `y` is *not* `2`. – akuzminykh Jul 16 '20 at 00:13
  • You are right. This was a disastrous mistake. I forgot that primitive types behave different. I edited the answer, thank you. – Darkmoon Chief Jul 16 '20 at 00:28
  • 1
    Unfortunately, you've choosen `Integer` for the demonstration, which is pass-by-value here. Therefore your example is still plain wrong as the value of `y` is `4`. You've used a deprecated constructor as well. – akuzminykh Jul 16 '20 at 00:42