方法是否与对象一起实例化?

Does a method get instantiated together with an object?

假设我得到以下 class:

public class Human(){

    String eyeColor;

    public Human(String faceDescription){
           this.eyecolor = determineEyeColor(faceDescription);
    }

    private String determineEyeColor(String faceDescription){
          String eyeColor;
          <algorithm that extracts the actual eye color substring">
          return eyeColor;
    }
}

在我的主要方法中,我接到了这样的电话:

String faceDescription = "<String where a face gets described in detail>";
Human human = new Human(faceDescription);

如果我现在形成一个包含 10 000 个 Human() 对象的列表。 determineEyeColor() 方法(因为它位于人类内部 class)是否也被实例化了 10 000 次,因此是一个很大的内存槽?如果我这样编程,在资源方面是否有实质性差异

public class Human(){

   String eyeColor;

   public Human(String eyeColor){
          this.eyecolor = eyeColor;
   }
}

将 determineEyeColor() 方法放在 Human 的 ** 之外 ** class 并以这种方式在我的主要方法中进行调用:

String faceDescription = "<String where a face gets described in detail>";
Human human = new Human(determineEyeColor(faceDescription));

该方法也会在每个实例化时被调用。 determineEyeColor() 本身的代码块在我的整个代码中也只写了 1 次。

唯一的区别是 算法本身 不会在每个对象中实例化,对吗?我基本上在每个 Human() 实例中都没有 10 000 x determineEyeColor()。

这样做的缺点是我不能立即在其他程序上重用这个 class,因为我还需要对实例化 class 进行更改(将 determineEyeColor() 添加到实例化 class).

这是真的吗?该方法是在每个 Human() 实例中实例化还是 Java 识别并在所有对象上共享该方法,仅使用映射到 Human() 的相应实例的不同字段。

有很多方法可以做到这一点。 的确,如果您为每个输入实例化并在范围内维护一个人类对象,那么将会存在很多人类对象,但是如果在您的处理结构中,人类对象超出范围,那么垃圾收集最终会整理为你准备。

关于是否应该在输入中包含字段,而不仅仅是字符串,存在着完全不同的争论,但那是另一个问题。

在面向对象编程中,class 的一个实例只保存数据。方法属于 class 并且代码在所有对象之间共享。

数据(对象的属性)的目的是确定方法的行为方式。因此,根据数据的不同,每个方法的行为都会有所不同,但是每个对象的方法代码都不会改变。

当您实例化 class Human 的 10 000 个对象时,您正在为数据创建 10 000 个容器,并与 Human class 的实现相关联。这意味着您可以在每组数据上执行 Human class 的方法。尽管执行相同的代码块,但调用对象的方法可能会产生不同的结果。