JAVA CONSTRUCTOR
JAVA CONSTRUCTOR
JAVA
LECTURE : CONSTRUCTOR
A. K. SIROMONI
( AIML )
CONSTRUCTOR
// Declaring Constructor
import java.util.*;
A.K.SIROMONI STCET(AIML) 3
CONSTRUCTOR
EXAMPLE 2 - FILE NAME (myclass2.java)
OUTPUT : 5 myclass2
A.K.SIROMONI STCET(AIML) 4
CONSTRUCTOR
EXAMPLE 3 - FILE NAME (myclass3.java)
A.K.SIROMONI STCET(AIML) 5
CONSTRUCTOR
EXAMPLE 4 - FILE NAME (myclass4.java)
public myclass4(){val =4 ;}
OUTPUT : 4
10
A.K.SIROMONI STCET(AIML) 6
COPY CONSTRUCTOR
EXAMPLE 9 - FILE NAME (function8.java)
//COPY CONSTRUCTOR
// Compare result with output of Example 7
import java.io.*;
class one { int i;
String c;
one( one o ){ this.i = o.i; this.c = "b"+o.c;} // copy constructor
one(int i, String s){this.i = i; c=s; }
void incr(){ i++;}
void tell(){ System.out.println("object "+c+" is having value "+i);} }
public class function8{
public static void main(String [] args){ OUTPUT :
one a = new one(11,"a"); object a is having value 11
// calling copy constructor object ba is having value 11
one b = new one(a); object a is having value 11
one c = a; after change
a.tell(); b.tell(); a.incr(); object a is having value 12
System.out.println("after change"); object ba is having value 11
a.tell(); b.tell(); c.tell(); object a is having value 12
} }
A.K.SIROMONI STCET(AIML) 7
CONSTRUCTOR
EXAMPLE 5 - FILE NAME (myclass5.java)
// Declaring a member to be final and trying to change it
import java.util.*;
public class myclass5 {
public int i; public char c; public float f;public boolean b;
myclass5(int i, char c, float f, boolean b){
this.i = i ; this.c = c ; this.f = f; this.b = b;}
A.K.SIROMONI STCET(AIML) 8
CONSTRUCTOR
EXAMPLE 5 - FILE NAME (myclass5.java)
// Correct as we are not changing final member
import java.util.*;
public class myclass5 {
public int i; public char c; public float f;public boolean b;
myclass5(int i, char c, float f, boolean b){
this.i = i ; this.c = c ; this.f = f; this.b = b;}
A.K.SIROMONI STCET(AIML) 9
CONSTRUCTOR
EXAMPLE 6 - FILE NAME (myclass6.java)
// Using finally block for try and exception block
import java.util.*;
A.K.SIROMONI STCET(AIML) 10