java - Smalltalk 与 java 中的实例变量

标签 java encapsulation smalltalk instance-variables getter-setter

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

在此示例中,ford 和 honda 是同一类 Car 的两个实例。 福特如何使用本田对象的里程,反之亦然?这是我的实际问题。对不起,如果这太天真了

最佳答案

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 中,类的实例可以访问同一类的另一个实例的私有(private)字段。

对于具有两个字段xy 的类Pointequals 方法的常见实现(实际上由 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;
}

在这种情况下,当前对象正在直接访问另一个对象 point 的字段,这在 Smalltalk 中是不允许的。

这在 C# 和许多其他语言中也是允许的。我不确定 Smalltalk 是否真的是唯一不允许使用它的语言。

按照惯例,Smalltalk 类的访问器通常与实例变量相同,但您需要实际编写访问器,并且没有直接访问不同实例上的字段的语法。

关于java - Smalltalk 与 java 中的实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22733171/

相关文章:

java - 在java中从parse.com转换时间戳

oop - smalltalk 反射 - 如何获取方法名称?

widget - 在 Spec 中添加一行会导致一列?

java - 通过 native SQL删除的子实体仍然存在于entityManager中

java - 我的 JAVA 应用程序的外部插件框架

java - 按照正确的 OO 设计使用另一个对象的功能 - 封装

php - Symfony2 : get security. 实体类中的上下文

random - 如何从 Smalltalk 的集合中获取特定数量的随机元素?

java.sql.SQLException : Geometry byte string must be little endian

swift - 封装对清除变量或常量的类型有何作用?