Constructors and Method Overloading 2022
Constructors and Method Overloading 2022
Constructors, Method
Overloading
1
Object Initialisation
When objects are created, the initial value of data fields is
unknown unless its users explicitly do so.
In many cases, it makes sense if this initialisation can be
carried out by default without the users explicitly initializing
them.
In Java, this can be achieved though a mechanism called
constructors.
2
What is a Constructor?
Constructor is a special method that gets invoked
“automatically” at the time of object creation.
3
Defining a Constructor
Like any other method
public class ClassName {
// Data Fields…
// Constructor
public ClassName()
{
// Method Body Statements initialising Data Fields
}
//Methods to manipulate data fields
}
Invoking:
When the object creation statement is executed, the
constructor method will be executed automatically.
4
Defining a Constructor: Example
public class Counter {
int CounterIndex;
// Constructor
public Counter()
{
CounterIndex = 0;
}
//Methods to update or access counter
public void increase()
{
CounterIndex = CounterIndex + 1;
}
public void decrease()
{
CounterIndex = CounterIndex - 1;
}
int getCounterIndex()
{
return CounterIndex;
}
}
5
Trace counter value at each statement and
What is the output ?
public class Counter {
int CounterIndex;
System.out.println(counter1.getCounterIndex());
} public Counter(int InitValue )
} {
CounterIndex = InitValue;
} 6
A Counter with User Supplied Initial Value ?
This can be done by adding another constructor
method to the class.
public class Counter {
int CounterIndex;
// Constructor 1
public Counter()
{
CounterIndex = 0;
}
public Counter(int InitValue )
{
CounterIndex = InitValue;
}
}
7
Adding a Multiple-Parameters Constructor to
our Circle Class
8
Constructors initialise Objects
9
Constructors initialise Objects
10
Multiple Constructors
11
Multiple Constructors
public class Circle {
public double x,y,r; //instance variables
// Constructors
public Circle(double centreX, double cenreY, double radius) {
x = centreX; y = centreY; r = radius;
}
public Circle(double radius) { x=0; y=0; r = radius; }
public Circle() { x=0; y=0; r=1.0; }
12
Initializing with constructors
public class TestCircles {
circleA = new Circle(10, 12, 20) circleB = new Circle(10) circleC = new Circle()
name
number of arguments
type of arguments
position of arguments
14
15