constructors
What is the exact advantage of using constructors?
What is the exact advantage of using constructors?
you have to use constructors to create an actual object of some type...
for example if you had a class myObject..
public class MyObject
{
private String name;
// the constructor
public MyObject( // some parameters .. say String name );
{
/* initialize some stuff.. set the name of THIS myObject to be
the same as the name passed in the constructor
*/
this.name = name;
}
public String getName()
{
return name;
}
}
Now somewhere else in your code, you can create an instance of MyObject and use it like this..
//first create the actual object. This calls the constructor of MyObject.
MyObject mo = new MyObject( "MyName" );
//then call any of the methods in our object like..
String objectsName = mo.getName();
Understand?
You HAVE to have a constructor in your object if you want to create an instance of that object.
For example, you could create several instances of MyObject each with a different name.
Hope this helps..
> You HAVE to have a constructor in your object if you want to create an instance of that object.
<nitpick>
Be careful of what you say
</nitpick>
class Foo {
public String toString() {
return "bar";
}
public static void main(String[] args) {
Foo f = new Foo();
System.out.println(f);
}
}
There's a constructor in that Foo - it's the default one that the compiler gives you.
Best to understand what's going on here.
%
Yes I do understand duffman. What I was highlighting was that post sounded like you HAVE to write a constructor but you can have a class where you DO NOT write a constructor.
Also that statement is moot becuase you cannot have a class without a constructor. As you pointed out they will at least have a default constructor.