Thursday, September 15, 2011

Overloaded Constructors

Here's how we can overload constructors - and use any one of them at create time.

browse

package org.megha.blog.example.part3;

/**
 * Represents a person, with a name and a title.
 */
public class Person {

	private String name;
	private String title;

	/** creates a {@link Person} with a name and a title */
	public Person(String name, String title) {
		this.name = name;
		this.title = title;
	}

	/** creates a {@link Person} with only a name (title is set to UNKNOWN) */
	public Person(String name) {
		this(name, "UNKNOWN"); // calls the previous constructor
                                       // with title as UNKNOWN
	}

	/** creates a {@link Person} without a name or a title */
	public Person() {
		this("NO_NAME"); 
                // note how the one-arg constructor is called, 
                // which calls the two arg constructor
	}

	public void print() {
		System.out.println("----------------------");
		System.out.println("Name = " + name);
		System.out.println("Title = " + title);
	}

	public static void main(String args[]) {
		// Person class has overloaded constructors,
                // and we can call any of these.
		Person person1 = new Person();
		Person person2 = new Person("Sam");
		Person person3 = new Person("Sam","Engineer");

		person1.print();
		person2.print();
		person3.print();
	}
}
Output of this program:
----------------------
Name = NO_NAME
Title = UNKNOWN
----------------------
Name = Sam
Title = UNKNOWN
----------------------
Name = Sam
Title = Engineer

1 comment:

  1. Mystino Games for Real Money at Casinos in MN
    Mystino games are available to play in our bet365 full-scale online casino games area. These happyluke games include slots, table games, video ミスティーノ poker, blackjack,

    ReplyDelete