java问题:这是一种方法吗?

Ste*_*fan 5 java oop variables class

我不是Java人,所以我问自己这意味着什么:

public Button(Light light) {
        this.light = light;
}
Run Code Online (Sandbox Code Playgroud)

按钮是一种方法吗?我问自己,因为它需要一个输入参数灯.但如果它是一种方法,为什么它会以大写字母开头并且没有返回数据类型?

这是一个完整的例子:

public class Button {
  private Light light;

  public Button(Light light) {
    this.light = light;
  }

  public void press() {
    light.turnOn();
  }
}
Run Code Online (Sandbox Code Playgroud)

我知道,这个问题真是微不足道.但是,我与Java没有任何关系,也没有找到上面关于Button的描述.我只是感兴趣.

kgr*_*rad 11

Button是一个构造函数.


Osc*_*Ryz 11

这是一个非常有效的问题.

你认为它是一个方法构造函数,它基本上具有你刚才提到的特性:

  • 没有返回类型(因为它正在构造类的实例)
  • 它们以类名命名,在这种情况下类是Button (大写没有什么特别,但是编码约定,java类应该以大写开头,因此构造函数也以大写开头)

关于您发布的代码的其他说明.

如果您没有定义构造函数,编译器将为您插入一个无参数构造函数:

所以这是有效的:

public class Button {
    // no constructor defined
    // the compiler will create one for you with no parameters
}

.... later 
Button button = new Button(); // <-- Using no arguments works.
Run Code Online (Sandbox Code Playgroud)

但是如果你提供另一个构造函数(就像你的情况一样),你就不能再使用no args构造函数了.

public class Button(){
    public Button( Light l  ){ 
        this.light = l;// etc
    }
    // etc. etc. 
 }
 .... later 

 Button b = new Button(); // doesn't work, you have to use the constructor that uses a Light obj
Run Code Online (Sandbox Code Playgroud)