I have just started programming with Java. The text we use is lacking when talking about methods and constructors. I'm not sure what a method or a constructor is exactly and what makes each unique. Can someone please help me define them and differentiate between the two?
The important difference between constructors and methods is that constructors initialize objects that are being created with the new
operator, while methods perform operations on objects that already exist.
Constructors can't be called directly; they are called implicitly when the new
keyword creates an object. Methods can be called directly on an object that has already been created with new
.
The definitions of constructors and methods look similar in code. They can take parameters, they can have modifiers (e.g. public
), and they have method bodies in braces.
Constructors must be named with the same name as the class name. They can't return anything, even void
(the object itself is the implicit return).
Methods must be declared to return something, although it can be void
.
The main difference is
1.Constructor are used to initialize the state of object,where as method is expose the behaviour of object.
2.Constructor must not have return type where as method must have return type.
3.Constructor name same as the class name where as method may or may not the same class name.
4.Constructor invoke implicitly where as method invoke explicitly.
5.Constructor compiler provide default constructor where as method compiler does't provide.
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