Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

View RSS Feed

JD1's Personal Development Blog

Constructors

Rate this Entry
We can use a constructor to quickly initialise variables as soon as our object is created. If you haven't read the above post, please do - you will become familiar with the code we're using for these examples.

Here's Class1.

class Class1{
	public static void main(String args[]){
		Class2 class2Object = new Class2("Tony");
		class2Object.outputName();
	}
}

You can see what we've done here is added an argument of "Tony" to our class2Object. To use this constructor, you must make a method with the exact same name as the class in which it's in. Take a look at our Class2 code.

public class Class2 {
	private String friendName;
 
	public Class2(String name){
		friendName = name;
	}
	public void setName(String name){
		friendName = name;
	}
	public String getName(){
		return friendName;
	}
	public void outputName(){
		System.out.printf("Your friend's name is %s", getName());
	}
}

You will notice this new method.

public Class2(String name){
		friendName = name;
	}

The method's name is Class2, identicle to that of our class name. Since we were able to send the name variable over to Class2 as the object was created, this now makes our setName method redundant. Its job has been taken care of.

Constructors are useful if we wanted to use multiple objects. Each object has its own set of variables. What we could do, if we wanted, would be to create another object like this.

Class2 class2Object2 = new Class2("Betty");

We could now decide to output class2Object2 or class2Object1; each would produce a different output.
Categories
Uncategorized

Comments