You are on page 1of 48

Constructors

• Implicit return type of a class’ constructor is the class type itself


• It is the constructor’s job to initialize the internal state of an object so
that the code creating an instance will have a fully initialized, usable
object immediately.

• When using the default constructor, all non initialized


instance variables will have their default values, which are zero,
null, and false, for numeric types, reference types, and boolean,
respectively.
Constructor
class Box class Test
{ {
double w,h,l;
Box() public static void main(String args[])
{ {
System.out.println (“constructing box”); Box mybox1 = new Box();
w=10;
h=10; Box mybox2=new Box();
l=10; double vol;
} vol = mybox1.volume();
double volume()
{ System.out.println(“Volume is ” + vol );
return(w*h*l); vol = mybox2.volume();
}
System.out.println(“Volume is ” + vol );
}
}}
mybox1-w=10 h=10l=10
mybox2 w=10 h=10 l=10
Parametrized Constructor

class Box class Test


{ {
int w,h,l; public static void main(String args[])
Box(int width, int length,int height) {
{ Box mybox1 = new Box(10,20,15);
w=width; Box mybox2=new Box(2,3,5);
h=height; double vol;
l= length; vol = mybox1.volume();
} System.out.println(“Volume is ” +
double volume() vol );
{ vol = mybox2.volume();
return(w*h*l); System.out.println(“Volume is ” + vol
} );
} }}
mybox1 –w = 10 h=20 l=15
mybox2 –w=2 h=3 l=5
Overloading methods

• Defining methods with same name and different parameter list is


called method overloading

• When an overloaded method is called then Java compiler checks


the type and number of arguments to determine which method
has to be called

• Changing only the return type does not lead to method


overloading. In this case program compilation gives error.

• It is a way of achieving polymorphism.


Example
class OverloadDemo class Overload
{ {
void sum(int x, int y) public static void main(String args[])
{ {
System.out.println(x+y); OverloadDemo ob= new OverloadDemo();
}
ob.sum(2,3);
void sum(float x, float y)
ob.sum(2.5,3.5);
{
ob.sum(2,3,5);
System.out.println(x+y);
} }
void sum(int x, int y, int z) ]
{
System.out.println(x+y+z);
}

}
Automatic type conversion apply to
overloading
class OverloadDemo class Overload{
{
void test() public static void main(String args[])
{ {
System.out.println(“No Parameter”); OverloadDemo ob= new OverloadDemo();
} int i =88;
void test(int a,int b) ob.test()
{ ob.test(10,20);
System.out.println(“a nd b” + a + “ ” + b); ob.test(i);
} ob.test(123.2);
void test(double a) }
{ }
Sytem.out.println(“Inside test(double) :”+a);
}
}
output
• No parameters
• a and b: 10 20
• Inside test(double) a: 88
• Inside test(double) a: 123.2
Overloading Constructors
Class Box Box()
{ {
double width; //instance variables width=-1;
double height; height=-1;
double depth; depth=-1;
Box(double w, double h, double d ) }
{
Box(double len)
width=w;10
{width= height= depth=len;
height=h;20
}
depth=d;15
}
Overloading Constructors

double volume()
{
return(width*height*depth);
} }
Class Overload
{
public static void main(String args[])
{
Box mybox1 = new Box(10,20,15);
Box mybox2=new Box();
Box mycube=new Box(7);
double vol;
vol = mybox1.volume();
System.out.println(“Volume is ” + vol );
vol = mybox2.volume();
System.out.println(“Volume is ” + vol);
vol=mycube.volume()
System.out.println(“Volume is ” + vol);
}}
Output
• Volume of mybox1 is 3000.0
• Volume of mybox2 is -1.0
• Volume of mycube is 343.0

• The proper overloaded constructor is called based upon the


arguments specified when new is executed.
Using Objects as Parameters
• We have only been using simple types as parameters to methods.
• However, it is both correct and common to pass objects to methods
Object as parameter
class PassOb {
// Objects may be passed to methods.
public static void main(String args[]) {
class Test {
Test ob1 = new Test(100, 22);
int a, b;
Test ob2 = new Test(100, 22);
Test(int i, int j) {
Test ob3 = new Test(-1, -1);
a = i;
b = j;
System.out.println("ob1 == ob2: " +
} ob1.equalTo(ob2));
// return true if o is equal to the //invoking
object
System.out.println("ob1 == ob3: " +
boolean equalTo(Test o) { ob1.equalTo(ob3));
if(o.a == a && o.b == b) }
return true; }
else
return false;
}
• /* Here, Box defines three constructors to class OverloadCons {
initialize
public static void main(String args[]) {
the dimensions of a box various ways.
// constructor used when // create boxes using the various constructors
*/
cube is created Box mybox1 = new Box(10, 20, 15);
class Box {
Box mybox2 = new Box();
double width; Box(double len) {
Box mycube = new Box(7);
double height; width = height = depth = len;
double depth;
} double vol;

// constructor used when all dimensions specified


// get volume of first box
Box(double w, double h, double d) { // compute and return vol = mybox1.volume();
width = w; volume System.out.println("Volume of mybox1 is " +
height = h; vol);
double volume() {
depth = d;
}
return width * height * // get volume of second box
depth; vol = mybox2.volume();
// constructor used when no dimensions specified } System.out.println("Volume of mybox2 is " +
vol);
Box() { } // get volume of cube
width = -1; // use -1 to indicate
vol = mycube.volume();
height = -1; // an uninitialized
System.out.println("Volume of mycube is " +
depth = -1; // box vol);
} }
One object to initialize another
• One of the most common uses of object parameters involves
constructors.
• Frequently, we will want to construct a new object so that it is initially
the same as some existing object. To do this, we must define a
constructor that takes an object of its class as a parameter.

• For example, the following version of Box allows one object to


initialize another:
// Here, Box allows one object to initialize another.
class Box {
double width; // constructor used when no dimensions specified
double height; Box() {
double depth; width = -1; // use -1 to indicate
height = -1; // an uninitialized
// construct clone of an object depth = -1; // box
Box(Box ob) }
{
// pass object to constructor // constructor used when cube is created
width = ob.width; Box(double len) {
height = ob.height; width = height = depth = len;
depth = ob.depth; }
}
// constructor used when all // compute and return volume
dimensions //specified double volume() {
Box(double w, double h, double d) { return width * height * depth;
width = w; 10 }
height = h; 20 }
depth = d; 15
}
Box allows one object to initialize another.
class OverloadCons2 {
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);
Box myclone = new Box(mybox1);
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 cube is " + vol);
// get volume of clone
vol = myclone.volume();
// Simple Types are passed by value.

class Test { class CallByValue {


void meth(int i, int j) public static void main(String args[])
{ {
i *= 2; // i=i*2 30 Test ob = new Test();
j /= 2; // j=j/2 10 int a = 15, b = 20;
}
} System.out.println("a and b before call: " + a + " " + b);

ob.meth(a, b);

System.out.println("a and b after call: " + a + " " + b);


}
}
We work on the copies of the variables.i and j are the copies of
the variables a and b
The output from this program is shown here:

• a and b before call: 15 20


• a and b after call: 15 20
// Simple Types are passed by value
• Thus, a copy of the argument is made, and what occurs to the
parameter that receives the argument has no effect outside the
method.
Objects are passed through their references.

class Test { class PassObjRef {


int a, b; public static void main(String args[])

Test(int i, int j) { {
Test ob = new Test(15, 20);
a = i; 15
System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b);
b = j; 20
ob.meth(ob);
}
System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b);
// pass an object
}
void meth(Test o) {
}
o.a *= 2; // o.a=o.a*2 15*2=30
o.b /= 2; // 20/2=10
}
}
Output
• Changes to the object inside the method do affect the object used as
an argument.

• This program generates the following output:


• ob.a and ob.b before call: 15 20
• ob.a and ob.b after call: 30 10
One-Dimensional Arrays
• A one-dimensional array is, essentially, a list of like-typed variables
The general form of a one-dimensional array declaration is
• type var-name[ ];
• Here, type declares the element type (also called the base type) of
the array.
• The element type determines the data type of each element that
comprises the array. Thus, the element type for the array determines
what type of data the array will hold.
• int month_days[];
One-Dimensional Arrays
• month_days is an array variable, no array actually exists. To link
month_days with an actual, physical array of integers, you must
allocate one using new and assign it to month_days.
• new is a special operator that allocates memory
• array-var = new type [size];

• month_days = new int[12];


• all elements in the array will be initialized to zero
One-Dimensional Arrays
• array-var = new type [size];
• Thus, in Java all arrays are dynamically allocated
Two Dimensional Arrays
• int twoD[][] = new int[4][5];
class Array {
public static void main(String args[]) {
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
// An improvied version of the previous program.
class AutoArray {
public static void main(String args[]) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
System.out.println("April has " + month_days[3] + " days.");
}
}
Average an array of values.

class Average {
public static void main(String args[]) {
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
int i;
for(i=0; i<5; i++)
result = result + nums[i];

System.out.println("Average is " + result / 5);


}
}
// Search an array using for-each style for.

class Search {
public static void main(String args[]) {
int nums[] = { 6, 8, 3, 7, 5, 6, 1, 4 };
int val = 5;
boolean found = false;
// use for-each style for to search nums for val
for(int x : nums) {
if(x == val) {
found = true;
break;
}
}
if(found)
System.out.println("Value found!");
}
Array
class Length {
public static void main(String args[]) {
int a1[] = new int[10];
int a2[] = {3, 5, 7, 1, 8, 99, 44, -10};
int a3[] = {4, 3, 2, 1};

System.out.println("length of a1 is " + a1.length);


System.out.println("length of a2 is " + a2.length);
System.out.println("length of a3 is " + a3.length);
}
}
Array
• The size of an array—that is, the number of elements that an array
can hold—is found in its length instance variable.

This program displays the following output:


length of a1 is 10
length of a2 is 8
length of a3 is 4
// Pop an item from the stack

Program of stack int pop() {


if(tos < 0) {
System.out.println("Stack underflow.");
/ Improved Stack class that uses the length return 0;
array member.
class Stack { }
private int stck[]; else
private int tos; return stck[tos--];
}
// allocate and initialize stack }
Stack(int size) {
stck = new int[size]; class TestStack2 {
tos = -1; public static void main(String args[]) {
} Stack mystack1 = new Stack(5);
Stack mystack2 = new Stack(8);
// Push an item onto the stack // push some numbers onto the stack
void push(int item) { for(int i=0; i<5; i++) mystack1.push(i);
if(tos==stck.length-1) // use for(int i=0; i<8; i++) mystack2.push(i);
length member // pop those numbers off the stack
System.out.println("Stack is System.out.println("Stack in mystack1:");
full."); for(int i=0; i<5; i++)
else System.out.println(mystack1.pop());
stck[++tos] = item;
} System.out.println("Stack in mystack2:");
for(int i=0; i<8; i++)
System.out.println(mystack2.pop());
}
Nested Loops
class Nested {
public static void main(String args[]) {
int i, j;

for(i=0; i<10; i++) {


for(j=i; j<10; j++)
System.out.print(".");
System.out.println();
}
}
}
output
..........
.........
........
.......
......
.....
....
...
..
.
Program of stack
class TestStack {
public static void main(String args[]) {
Stack mystack1 = new Stack();
Stack mystack2 = new Stack();

// push some numbers onto the stack


for(int i=0; i<10; i++) mystack1.push(i);
for(int i=10; i<20; i++) mystack2.push(i);

// pop those numbers off the stack


System.out.println("Stack in mystack1:");
for(int i=0; i<10; i++)
System.out.println(mystack1.pop());

System.out.println("Stack in mystack2:");
for(int i=0; i<10; i++)
System.out.println(mystack2.pop());
}
Output
This program generates the following output:
Stack in mystack1:
9
8
7
6
5
4
3
2
1
0
Stack in mystack2:
19
18
17
16
15
14
13
12
Returning Object
class Test { class RetOb {
int a; public static void main(String args[]) {
Test ob1 = new Test(2);
Test(int i) { Test ob2;
a = i;
} ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
Test incrByTen() { System.out.println("ob2.a: " + ob2.a);
Test temp = new Test(a+10);
return temp; ob2 = ob2.incrByTen();
} System.out.println("ob2.a after second increase: "
} + ob2.a);
}
}
The output generated by this program is shown here:

• ob1.a: 2
• ob2.a: 12
• ob2.a after second increase: 22
Explanation
Each time incrByTen( ) is invoked, a new object is created, and a reference to it is
returned to the calling routine.
This program makes another important point: Since all objects are
dynamically allocated using new, you don’t need to worry about an object
going out-of-scope because the method in which it was created terminates.

The object will continue to exist as long as there is a reference to it somewhere in


your program.
/ /Demonstrate static variables, methods, and blocks.

class UseStatic {
static int a = 3;
static int b;
static void meth(int x)
{
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static {
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[]) {
meth(42);
}
}
Static Keyword
• As soon as the UseStatic class is loaded, all of the static statements are run.
• First, a is set to 3, then the static block executes, which prints a message and
then initializes b to a*4 or 12.
• Then main( ) is called, which calls meth( ), passing 42 to x. The three
println( ) statements refer to the two static variables
• a and b, as well as to the parameter x.
Here is the output of the program:
Static block initialized.
x = 42
a=3
b = 12
Static Keyword
• It is possible to create a member that can be used by itself, without reference to a specific
instance.

• To create such a member, precede its declaration with the keyword static.

• When a member is declared static, it can be accessed before any objects of its class are created,
and without reference to any object.

• You can declare both methods and variables to be static. The most common example of a static
member is main( ).

• main( ) is declared as static because it must be called before any objects exist.
Static Keyword
• Instance variables declared as static are, essentially, global variables.
When objects of its class are declared, no copy of a static variable is
made.
• Instead,all instances of the class share the same static variable
• Methods declared as static have several restrictions:
• They can only directly call other static methods of their class.
• They can only directly access static variables of their class.
• They cannot refer to this or super in any way. (The keyword super
relates to inheritance)
Static Keyword
• Outside of the class in which they are defined, static methods and
variables can be used independently of any object.

• To do so, you need only specify the name of their class followed by
the dot operator

• classname.method( )
Static Keyword
class StaticDemo
{
static int a = 42;
static int b = 99;
static void callme() {
System.out.println("a = " + a);
}
}

class StaticByName {
public static void main(String args[]) {
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);
}
}
Static Keyword
• Here is the output of this program:
• a = 42
• b = 99
• Inside main( ), the static method callme( ) and the static variable b
are accessed through their class name StaticDemo.

You might also like