constructors

What is the exact advantage of using constructors?

[57 byte] By [Raghu_nca] at [2007-11-27 11:45:26]
# 1

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..

smithdale87a at 2007-7-29 18:01:44 > top of Java-index,Java Essentials,New To Java...
# 2

> 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);

}

}

floundera at 2007-7-29 18:01:44 > top of Java-index,Java Essentials,New To Java...
# 3

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.

%

duffymoa at 2007-7-29 18:01:44 > top of Java-index,Java Essentials,New To Java...
# 4

> What is the exact advantage of using constructors?

As opposed to what alternative?

%

duffymoa at 2007-7-29 18:01:44 > top of Java-index,Java Essentials,New To Java...
# 5

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.

floundera at 2007-7-29 18:01:44 > top of Java-index,Java Essentials,New To Java...
# 6

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.

floundera at 2007-7-29 18:01:44 > top of Java-index,Java Essentials,New To Java...