Lab # 6 Method and Constructor Overloading: Introducing
Lab # 6 Method and Constructor Overloading: Introducing
LAB # 6
OBJECTIVE:
To Study method overloading, constructor overloading.
THEORY:
In Java it is possible to define two or more methods within the same class that
share the same name, as long as their parameter declarations are different.
When this is the case, the methods are said to be overloaded, and the
process is referred to as method overloading. Method overloading is one of
the ways that Java implements
polymorphism.
Constructors are methods that can be overloaded, just like any other method
in a class. In most situations, you will want to generate objects of a class from
different sets of initial defining data. If you just consider the Sphere class, you
could conceive of a need to define a Sphere object in a variety of ways. You
might well want a constructor that accepted just the (x, y, z) coordinates of a
point, and have a Sphere object created with a default radius of 1.0. Another
possibility is that you may want to create a default Sphere with a radius of 1.0
positioned at the origin, so no arguments would be specified at all. This
requires two constructors in addition to the one you have already written. Let’s
try it then
The statements in the default constructor that set three fields to zero are not really necessary,
as the fields would be set to zero by default. They are there just to emphasize that the primary
purpose of a constructor is to enable you to set initial values for the fields. If you add the
following statements to the Create Spheres class, you can test out the new constructors:
Another Example:
class OverloadCons {
public static void main(String args[]) {
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
LAB TASK
1. Write a program that creates two classes one is Employee and another
is the main method class. Employee class contains emp_code, name,
designation and salary fields, and three constructors; one is a default
constructor, the second constructor contains three field emp-code,
name, and designation and if the designation is clerk set salary of Rs.
5000 if the designation is peon set salary of Rs. 2000 and if manager
set salary of Rs. 10000 for others set the salary of Rs. 1000 and third
constructor contain four fields emp_code, name, designation, and
salary. Display information of employee using display method In Java.
ASSIGNMENT