Bellow is an example I found on Tutorials Points, an example of a constructor. I got most of them, but I just don't get why you need a constructor and a method.
public Puppy(String name){
System.out.println("Passed Name is :" + name );
}
My question is, what stops you from doing this instead?
public static void Puppy(String name){
System.out.println("Passed Name is: "+name);
}
Doesn't these two do the same thing once called?
Here is the full program for reference:
public class Puppy {
int puppyAge;
public Puppy(String name) {
System.out.println("Passed Name is :" + name);
}
public void setAge(int age) {
puppyAge = age;
}
public int getAge() {
System.out.println("Puppy's age is :" + puppyAge);
//what does this return do? since the puppyAge is already printed above.
return puppyAge;
}
public static void main(String []args){
Puppy myPuppy = new Puppy("tommy");
myPuppy.setAge(2);
myPuppy.getAge();
System.out.println("Variable Value :" + myPuppy.puppyAge);
}
}
I guess your question is why the constructor is created using...
...instead of...
..., right?
If it is, firstly you should now that a constructor is a special method owned by a class that is called whenever you create a new instance of that class. So if, for example, you have this class...
..., then whenever you create a new instance of this class like...
..., the constructor will be called and that method will be executed. (In this example, it would print "Hello World" on the screen.)
That said, you can see that the constructor is a method, but it's a special method called when the class is instantiated. So, regarding your question, the reason why the constructor is right this way instead of a regular method header is to indicate to the compiler that it is a constructor and not a regular method. If you write
public void Clazz ()
instead ofpublic Clazz ()
, then the compiler will not recognize your constructor, and will think it's just a regular method.Note that constructors never return anything, so it would not be necessary to use the void keyword. Also, there's no sense in making a constructor static, since the constructor is called when a new object is instantiated.
A constructor is supposed to be for setting up the object where as a method simply does some action with the object. Java is object oriented so the whole language revolves around the object. Constructors also can not return anything and must be used with new to return an instance of the object created where as methods can return anything or nothing at all.