Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java question: Is it a method?

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.

like image 249
Stefan Avatar asked Mar 17 '10 18:03

Stefan


People also ask

What are the methods in Java?

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.

What is an example of a method in Java?

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.


2 Answers

Button is a constructor.

like image 136
kgrad Avatar answered Sep 25 '22 11:09

kgrad


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
like image 20
OscarRyz Avatar answered Sep 21 '22 11:09

OscarRyz