Classes and Objects in Java: Constructors, Overloading, Static Members
Classes and Objects in Java: Constructors, Overloading, Static Members
Iqbal Khattra
1
Circle Program
2
}
Object Initialisation
4
When objects are created, the initial value of data fields is unknown unless its users
explicitly do so. For example,
ObjectName.DataField1 = 0; // OR
In many cases, it makes sense if this initialisation can be carried out by default without the
users explicitly initializing them.
For example, if you create an object of the class called “Counter”, it is natural to assume that the
counter record-keeping field is initialized to zero unless otherwise specified differently.
class Counter
{
int CounterIndex;
…
}
Counter counter1 = new Counter();
A class can have more than one constructor as long as they have
different signature (i.e., different input arguments syntax).
Defining a Constructor
6
Invoking:
There is NO explicit invocation statement needed: When the object
creation statement is executed, the constructor method will be executed
automatically.
Defining a Constructor: Example
7
int getCounterIndex()
{
return CounterIndex;
}
}
Trace counter value at each statement
8
class MyClass
{
public static void main(String args[])
{
Counter counter1 = new Counter();
counter1.increase();
int a = counter1.getCounterIndex();
counter1.increase();
int b = counter1.getCounterIndex();
if ( a > b )
counter1.increase();
else
counter1.decrease();
System.out.println(counter1.getCounterIndex());
}
}
Counter Constructor
9
// Constructor 1
public Counter()
{
CounterIndex = 0;
}
public Counter(int InitValue )
{
CounterIndex = InitValue;
}
}
{
x = centreX;
y = centreY;
r = radius;
}
//Methods to return circumference and area
public double circumference() { return 2*3.14*r; }
public double area() { return 3.14 * r * r; }
}
Constructors initialise Objects
11
circleA = new Circle(10, 12, 20) circleB = new Circle(10) circleC = new Circle()
nCircles = Circle.numCircles;
Static Variables - Example
22
Using static variables:
// Constructors...
Circle (double x, double y, double r){
this.x = x;
this.y = y;
this.r = r;
numCircles++;
}
}
Class Variables - Example
23
Using static variables:
numCircles
Instance Vs Static Variables
24
class MyClass {
public static void main(String args[])
{ Directly accessed using ClassName (NO Objects)
String s1 = "Melbourne";
String s2 = "Sydney";
String s3 = "Adelaide";
int a = 10;
int b = 20;