Smalltalk Vs java中的实例变量
作者:互联网
在Pharo by Example Book中,我读到了
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.
我认为它对Java或c#等其他语言也很常见.类的实例无法访问同一个类的另一个实例的实例变量.它仅适用于smalltalk?
In Smalltalk, two instances of the same class cannot access each other’s
instance variables unless the class defines “accessor methods”
实例如何使用访问器方法访问另一个实例的实例变量?
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();
}
在这个例子中,福特和本田是同一类汽车的两个实例.福特如何使用本田对象的里程数,反之亦然?这是我的实际问题.对不起,如果这太天真了
解决方法:
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 ?
对不起,但这种想法不正确.
在Java中,类的实例可以访问同一个类的另一个实例的私有字段.
对于具有两个字段x和y的类Point,equals方法的常见实现(实际上由Intellij生成)是:
@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;
}
在这里,当前对象直接访问另一个对象点的字段,这在Smalltalk中是不允许的.
在C#和许多其他语言中也允许这样做. Smalltalk是否真的是禁止它的唯一语言我不确定.
按照惯例,Smalltalk类的访问器通常与实例变量相同,但您需要实际编写访问器,并且没有直接访问不同实例上的字段的语法.
标签:java,instance-variables,encapsulation,smalltalk,getter-setter 来源: https://codeday.me/bug/20190725/1531111.html