Search code examples
javaencapsulationsmalltalkinstance-variablesgetter-setter

Instance variables in Smalltalk Vs java


In Pharo by Example Book, I read

Instance variables in Smalltalk are private to the instance itself. This is in contrast to Java and C++, which allow instance variables (also known as “fields” or “member variables”) to be accessed by any other instance that happens to be of the same class.

I think it is common to other languages like Java or c# also . An instance of class cannot access instance variable of another instance of same class. How it is specific to smalltalk only ?

In Smalltalk, two instances of the same class cannot access each other’s instance variables unless the class defines “accessor methods”

How can an instance access another instance's instance variable using accessor method ?

using namespace std;
#include<iostream>
class car {
  private:
    int mileage;
  public:
    car(int); // Constructor
    int odometer();
};

car::car(int m) {
  mileage = m;
}

int car::odometer() {
  return mileage;
}

int main(void) {
  car ford(10000);
  car honda(20000);

  cout<<ford.odometer(); 
  cout<<honda.odometer();
}

In this example ford and honda are two instances of the same class Car. How ford can use the mileage of honda object or vice versa ? This is my actual question. Sorry if this is so naive


Solution

  • I think it is common to other languages like Java or c# also . An instance of class cannot access instance variable of another instance of same class. How it is specific to smalltalk only ?

    Sorry, but this thinking is incorrect.

    In Java, an instance of a class can access the private fields of another instance of the same class.

    For a class Point with two fields x and y, a common implementation of the equals method (in fact generated by Intellij) is:

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
    
        Point point = (Point) o;
    
        if (x != point.x) return false;
        if (y != point.y) return false;
    
        return true;
    }
    

    In this, the current object is accessing the fields of the other object point directly, as would not be allowed in Smalltalk.

    This is also allowed in C# and many other languages. Whether Smalltalk is really the only language disallowing it I'm not sure.

    By convention, the accessors of a Smalltalk class frequently are the same as the instance variable, but you need to actually write the accessors, and there is no syntax for accessing fields on a different instance directly.