Java问题:它是一个方法吗?

5

我不是Java专家,所以我想知道这意味着什么:

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

按钮是一个方法吗?我自问自答,因为它需要一个输入参数“light”。但如果它是一个方法,为什么会以大写字母开始并且没有返回数据类型呢?

下面是完整的示例:

public class Button {
  private Light light;

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

  public void press() {
    light.turnOn();
  }
}

我知道这个问题非常琐碎。然而,我对Java一无所知,也没有找到上面的Button的描述。我只是感兴趣。

7个回答

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.

但是如果你提供了另一个构造函数(就像在你的情况下),你将无法再使用无参构造函数。

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

好的,这很有道理。非常感谢你们提供如此详细的答案。这让我爱上了SO。 - Stefan

11

3

这是一个构造函数

在创建该类的实例时,您必须将light作为参数传递。

例如:

Light l = new Light();
Button b = new Button(l);
b.press();

2

这是Button类的一种可能的构造函数。任何包含类名且没有返回值的语句都是构造函数。

您可以定义多个构造函数,例如为了区分参数的数量和类型:

public Button();
public Button(int i);
public Button(int i, int j);
public Button(String s,int i, double d);

等等。


2

这是一个用于创建按钮对象的构造函数

因此,当您编写以下代码时:

Button myButton = new Button(new Light());

那个方法就是被调用的方法。

1
构造函数不是一个方法。 - Steve Kuo

0

0

这是在Button类中编写的自定义构造函数,它接受名为Light的自定义变量作为输入参数。 因此,在 Button 类中将有两个构造函数:

  1. 默认的,即 Button bt = new Button();
  2. 带参数的,即 Button bt = new Button(Light l),我们需要在初始化时传递这个

输入参数。


编译器不会生成默认构造函数,因此你的句子“因此,在Button类中你将有两个构造函数”是错误的。 - Tom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接