【问题标题】:Java OOP; creating several objectsJava面向对象;创建多个对象
【发布时间】:2021-07-29 07:50:51
【问题描述】:

我正在尝试将学生的数据存储在主课中,在学生课中我做了以下操作:

public class Student {
        public static String name = "UNKNOWN";
        Student(){

        }

        Student(String name) {
            this.name = name;}

虽然我主要做了以下事情:

public class Main {

    public static void main (String[] args) {
        //s1 is short for student1
        Student s1 = new Student ("Chris");
        Student s2 = new Student ("Layla");
        Student s3 = new Student ("Mark");

这个问题是,每当我打印一个 sx.name 时,我总是会打印最后一个。所以对于下面的代码:

System.out.println(s1.name);

我会得到 Mark,而应该是 Chris

【问题讨论】:

  • 只删除名称字段中的静态关键字

标签: java object constructor


【解决方案1】:

是的,因为静态字段由所有对象共享。 请按如下方式更改您的代码:

public class Student {
        public String name;
        Student(){

        }

        Student(String name) {
            this.name = name;

}

public static void main (String[] args) {
        //s1 is short for student1
        Student s1 = new Student ("Chris");
        Student s2 = new Student ("Layla");
        Student s3 = new Student ("Mark");
}

When to use static in java?

有时,您希望拥有所有对象共有的变量。 这是通过静态修饰符完成的。具有 声明中的静态修饰符称为静态字段或类 变量。它们与类相关联,而不是与任何 目的。类的每个实例共享一个类变量,即 在内存中的一个固定位置。任何对象都可以改变 a 的值 类变量,但类变量也可以在没有 创建类的实例。

【讨论】:

    【解决方案2】:

    静态变量name被实例访问,在Java中不推荐使用。您可以使其成为非静态的。 IDE(例如 IDEA)将为您提供有关此问题的一些提示/警告,例如:

    因此在 IDE 的帮助下,您可以轻松发现一些潜在问题。

    【讨论】:

      猜你喜欢
      • 2021-07-30
      • 1970-01-01
      • 2011-01-24
      • 2015-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多