What major difference between method and constructor in java?
also what mean of use this in method and constructor?
Thanks,
Swikar
Printable View
What major difference between method and constructor in java?
also what mean of use this in method and constructor?
Thanks,
Swikar
Constructor has the same name as the class name, but the method is not.
Really?
public class Foo {
public Foo() {
// a constructor
}
public void Foo() {
// a method with the same name as the class - not recommended, but perfectly valid
}
}
The difference is in intended usage, and the effect it has. A constructor is called to create an instance of a class, a method is called to perform some action. Every time you call a constructor (using the 'new' keyword, typically) a new instance is created. Not so with a method. We call constructors, as said, using the 'new' keyword, but call methods against either a reference to an object, or a class name, depending on whether it's a static method or not
Despite not actually being true??
No offence, but I think your original answer was superficial and misleading. The usage of contructors and methods vary enormously, what they're referred to as in source code is trivial. I can see someone reading your answer and saying "oh, so apart from them having different names, there's no difference between a method and a constructor", putting a load of unsuitable code in a constructor that belongs in a method, and creating loads of new instances because they call the constructor in order to run that code. Then they can't work out why their software doesn't work.
Actually I'm not talking about he usages of constructors, just want to tell how to separate those things.
Errrrr, ok
*shrug*
Just a misunderstand lol.