Showing posts with label overloaded. Show all posts
Showing posts with label overloaded. Show all posts

Thursday, September 15, 2011

Overloaded Methods

Here's an example that shows how methods can be overloaded.

browse

package org.megha.blog.example.part4;

import org.megha.blog.example.part2.Circle;
import org.megha.blog.example.part3.Person;

/**
 * A printer that can print a {@link Circle} or a {@link Person} or both.
 */
public class Printer {

	public void print(Circle circle) {
		System.out.println("printing circle...");
		circle.print();
	}

	public void print(Person person) {
		System.out.println("printing person...");
		person.print();
	}

	public void print(Circle circle, Person person) {
		System.out.println("printing circle and person");
		person.print();
		circle.print();
	}

	public void print(Person person, Circle circle) {
		System.out.println("printing person and circle");
		person.print();
		circle.print();
	}

	public static void main(String args[]) {

		Printer printer = new Printer();

		Circle circle1 = new Circle(8);
		Person person1 = new Person("Samuel", "Engineer");

		printer.print(circle1);
		printer.print(person1);
		printer.print(circle1, person1);
		printer.print(person1, circle1);
	}
}

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