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.
A method is a block of code which only runs when it is called. You can pass data, known as parameters, into a method. Methods are used to perform certain actions, and they are also known as functions.
Example 1: Java Methodsint result = obj. addNumbers(num1, num2); Here, we have called the method by passing two arguments num1 and num2 . Since the method is returning some value, we have stored the value in the result variable.
Button is a constructor.
That's a pretty valid question.
What your seeing it a method constructor which basically have the characteristics you have just mentioned:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With