【问题标题】:Why we use constructor in java [duplicate]为什么我们在java中使用构造函数[重复]
【发布时间】:2022-01-06 00:51:45
【问题描述】:

我知道构造函数是类的一个特殊成员,用于初始化数据成员。但是为什么我们真的需要构造函数,谁能告诉我。

【问题讨论】:

  • "...初始化数据成员" - 这正是使用构造函数的原因。它初始化新创建的实例。
  • 这能回答你的问题吗? Purpose of a constructor in Java?
  • 因为我们需要。根据定义,对象是使用构造函数创建的。这不是 Java 特定的,这是关于基于类的面向对象的开发。不过有些语言,比如臭名昭著的 ECMAScript 又名“JavaScript”复制/链接原型,而不是实例化类。

标签: java constructor


【解决方案1】:

我们可以使用构造函数来设置它的字段。

public class FutilePoint {
    
    private double x, y, size;
    private int color;
    
    public FutilePoint(double pos_x, double pos_y, double size, int color_RGB) {
        this.x = pos_x;
        this.y = pos_y;
        this.size = size;
        this.color = color_RGB;
    }

    public FutilePoint(pos_x, pos_y) {
        this.x = pos_x;
        this.y = pos.y;
        this.size = 4;
        this.color = 0x000000;
    }
}

然后我们可以创建许多不同的对象。

#import src.FutilePoint;

//somewhere in a random class...

public void doMeaninglessStuff() {
    for(int i = 1; i <= 99999999; i++) {
        for(int j = 1; j <= 99999999; j++) {
            new FutilePoint(i, j);
        }
    }
    new Point(0, 0, 128, 0xFFFF3A);
}

你也可以在构造函数中使用它的方法。

【讨论】:

    猜你喜欢
    • 2018-02-19
    • 1970-01-01
    • 2014-07-01
    • 2018-01-23
    • 2022-11-01
    • 2022-08-15
    • 2022-10-17
    相关资源
    最近更新 更多