I have been looking at it and it seems to be a method called 'Cat()', that is used to assign all of the data it defined into the Cat class's private instance variables.
If that assumption is correct, isn't this essentially just a set() method? Why isn't the name formatted like setCat(String name, int age, int weight, int strength) { ?
how would you describe: public Cat (String name, int age, int weight, int strength) { ?
Resolved
Comments (2)
- Popular
- New
- Old
You must be signed in to leave a comment
Guadalupe Gagnon
2 June 2020, 20:11
What you are seeing is called a constructor. It is not a method in that it has no return value:
Methods are described as:
[access modifier] [static/not] [return type] [method name] ([arguments]){
//code body
}
Optional↓-
Access Modifier - this can be public, protected, private, or left blank (blank would be called default and have the access as protected)
static - this can be included or left blank
Required↓-
Return Type - this MUST be included and the method MUST return a value specified here (you can use the keyword 'void' if the method should not return a value)
Method Name - MUST be included and follows normal java naming rules
Arguments - inside the parentheses. can be left blank. Multiple arguments separated by commas.
Below is an example of a method.
The return value in this method is an int so it MUST return a valid int. I could not do something like this:
A constructor, while similar to a method, has a few key differences. First, the constructor will only have one name and that is the name of the class. Second the static modifier is not allowed. And third it has no return value. So a constructor would look like this:
[access modifier] [name(has to be class name)] ([arguments])
In Java the constructor is called EVERY time an object of the class is made. Because this happens it is a convenient place to put the code to make the object valid. Before the "invention" of constructors, the initialize() method was the standard way of doing things, but this required users of objects to specifically call the initialize() method for each object they instantiated. If they forgot to call this then the object could potentially be problematic. Imagine writing thousands of lines of code that crash because you missed an initialize on line 235. +5
Gellert Varga
2 June 2020, 19:53
"how would you describe: public Cat (String name, int age, int weight, int strength) { ?"
This type of methods are named "constructor".
A set() method ("setter", for example setName() setAge() etc) is used if the object already exists.
The constructor method is used by Java when you are creating a new object:
You create a new Cat object here, and set its instancevariables immediately.
Of course, you can write such a method in your program if you need it:
but Java, when creating a new object, cannot use this to do immediate setting of instance variables for the new object. +1