views:

195

answers:

6

Hello,

I'm no Java guy, so I ask myself what this means:

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

Is Button a method? I ask myself, because it takes an input parameter light. But if it was a method, why would it begin with a capital letter and has no return data type?

Here comes the full example:

public class Button {
  private Light light;

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

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

I know, this question is really trivial. However, I have nothing to do with Java and haven't found a description for the Button thing above. I'm just interested.

+2  A: 

It is a constructor for the Button object.

So when you write:

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

That method is what gets called

mkoryak
The constructor is not a method.
Steve Kuo
+10  A: 

Button is a constructor.

kgrad
+3  A: 

Its a constructor.

You must pass light as a parameter when you create an instance of the class.

Eg

Light l = new Light();
Button b = new Button(l);
b.press();
Matt Joslin
+10  A: 

That's a pretty valid question.

What your seeing it a method constructor which basically have the characteristics you have just mentioned:

  • Do not have return type ( because it is constructing an instance of the class )
  • They are named after the class name, in this case the class is Button ( The uppercase is nothing special, but a coding convention, java classes should start with uppercase hence the constructor start with uppercase too )

And additional note about your posted code.

If you don't define a constructor, the compiler will insert a no-arguments constructor for you:

So this is valid:

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.

But if you supply another constructor ( like in your case ) you can't use the no args constructor anymore.

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
OscarRyz
Ok, this makes sense. Thank you all for the very detailed answers. This makes me love SO.
Stefan
+2  A: 

It's one of the possible constructor for the class Button. Every statement that contains the name of the class and has no return value is a constructor.

You can define multiple constructor, for instance for differentiating the number and type of parameters such:

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

and so on.

LucaB
A: 

Button is a constructor

Neeraj