UNIT 9 Constructor
UNIT 9 Constructor
UNIT 9 Constructor
Syntax:
class class_name
{
class_name() //constructor definition
{
// body of default constructor
}
class_name(parameters)
{
// body of parameterised constructor
}
. . . . . . . . .
. . . . . . . . .
public static void main(String [] args)
{
class_name object_name = class_name (); // call constructor. No need to object.
}
}
Example 1:
package alpha;
publicclass Constructor
{
Constructor() //default constructor
{
System.out.println("called constructor when object created");
}
publicvoid userdefinemethod() //user define method
{
System.out.println("called user define method through an object");
}
publicstaticvoid main(String args[])
__________________________________________________________________________________
Chapter 8
{
Constructor obj =newConstructor();
obj.userdefinemethod();
}
}
Output:
called constructor when object created
called user define method through an object
Constructors that does will take parameter then these Constructors are called as
“Parameterized Constructor“.
1. Constructor Can Take Value(s), Value(s) is/are Called as – “Argument“.
2. Arguments can be of any type i.e Integer, Character, Array or any Object.
3. Constructor can take any number of Arguments.
Rectangle () //constructor
{
length =0;
breadth =0;
}
Rectangle(int len,int bre) //parameterized constructor
{
length = len;
breadth = bre;
}
publicvoid display()
{
System.out.println("Length="+ length);
System.out.println("breadth="+ breadth);
}
}
publicclass RectangleDemo
{
publicstaticvoidmain(String args[])
{
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle(100,200);
System.out.println("r1 object length and breadth");
r1.display();
System.out.println("r2 object length and breadth");
__________________________________________________________________________________
Chapter 8
r2.display();
}
}
Output:
r1 object length and breadth
Length=0
breadth=0
r2 object length and breadth
Length=100
breadth=200
There is no copy constructor in java. But, we can copy the values of one object to another like
copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
By constructor
By assigning the values of one object into another
By clone() method of Object class
In this example, we are going to copy the values of one object into another using java
constructor.
Example 1:
package alpha;
publicclass Employee
{
intid;
String name;
public Employee(int i, String string)
{
id = i;
name = string;
}
Employee(Employee s)
{
id = s.id;
name =s.name;
}
void display()
{
System.out.println("id="+id);
System.out.println("name="+name);
}
publicstaticvoid main(String args[])
{
Employee e1 = new Employee(007,"jhon");
Employee e2 = new Employee(e1); //copy e1 object data into object e2
e1.display();
__________________________________________________________________________________
Chapter 8
e2.display();
}
}
Output:
id=7
name=jhon
id=7
name=jhon
publicclass MyOverloading
{
public MyOverloading()
{
System.out.println("called default constructor");
}
public MyOverloading(int i)
{
System.out.println("constructor parameterised with int value");
System.out.println("i="+i);
}
public MyOverloading(String str)
{
System.out.println("constructor parameterised with string object");
System.out.println("String Object is="+str);
}
public MyOverloading(int i,int j)
{
System.out.println("constructor parameterised with two integer arguments");
System.out.println("i="+i);
System.out.println("j="+j);
}
publicstaticvoid main(String a[])
{
MyOverloading m1 =newMyOverloading();
__________________________________________________________________________________
Chapter 8
MyOverloading m2 = newMyOverloading(10);
MyOverloading m3 = new MyOverloading(10,20);
MyOverloading m4 = newMyOverloading("methodoverloding demo");
}
}
Output:
called default constructor
constructor parameterised with int value
i=10
constructor parameterised with two integer arguments
i=10
j=20
constructor parameterised with string object
String Object is=methodoverloding demo
Example:
package alpha;
publicclass Chainingconstrucor
{
public Chainingconstrucor()
{
System.out.println ("In constructor...");
}
public Chainingconstrucor(int i)
{
this();
System.out.println ("In single parameter constructor...");
}
public Chainingconstrucor(int i, int j)
{
this(j);
System.out.println ("In double parameter constructor...");
}
publicstaticvoid main(String a[])
{
Chainingconstrucor ch = new Chainingconstrucor(10,20);
}
}
Output:
In constructor...
In single parameter constructor...
In double parameter constructor...
3.9 Different between method and constructor: [winter 2012, Nov dec 2011, dec 2010]
Constructor Method
Constructor no need to called, they are called In this case, we need call method through an
__________________________________________________________________________________
Chapter 8
this is a keyword in Java which can be used inside method or constructor of class.it works as
a reference to current object whose method or constructor is being invoked. this keyword can
be used to refer any member of current object from within an instance method or a
constructor. There are lot of use of this key word in java. ‘this’ is a reference variable that
refers to the current object.
Let us see below use of this key word.
‘this’ keyword can be used to refer current class instance variable.
‘this()’ can be used to invoke current class constructor.
‘this’ keyword can be used to invoke current class method (implicitly)
‘this’ can be passed as an argument in the method call.
‘this’ can be passed as argument in the constructor call.
‘this’ keyword can also be used to return the current class instance.
‘this’ Class
Object
reference
Use of ‘this’ references:If there is ambiguity between the instance variable and parameter,
this keyword resolves the problem of ambiguity.
Example 1:
package alpha;
publicclass Employee
{
intid;
String name;
System.out.println("name="+name);
}
publicstaticvoid main(String args[])
{
Employee e1 = new Employee(101,"jhon");
Employee e2 = new Employee(102,"carter");
e1.display();
e2.display();
}
}
Output:
id=101
name=jhon
id=102
name=carter
(a)static variable:
The static keyword in java is used for memory management. We can apply static keyword
on variables, methods, blocks and nested classes. Static keyword we cannot apply on top
level class means last outer class in java program. Static variables are associated with class
objects. Static variable value in java kept same value for each and every object Means static
variables value shared to all other objects in class. And we cannot use non static variable in
static method.
__________________________________________________________________________________
Chapter 8
See figure for illustration of non-static variable which is created memory for its own objects.
Example 1:
package alpha;
public class ClassA
{
public static int counter=0;
public void getcountervalue()
{
System.out.println("Value of counter="+counter);
}
public void countervalueincrease()
{
counter++;
}
public static void main(String [] args)
{
ClassA a1 =new ClassA();
ClassA a2 =new ClassA();
ClassA a3 =new ClassA();
System.out.println("print counter before increase value by a1 a2 and a3 objects");
a1.getcountervalue();
a2.getcountervalue();
a3.getcountervalue();
a1.countervalueincrease();
a2.countervalueincrease();
a3.countervalueincrease();
System.out.println("print counter After increase value by a1 a2 and a3 objects");
a1.getcountervalue();
a2.getcountervalue();
a3.getcountervalue();
}
}
Output:
print counter before increase value by a1 a2 and a3 objects
Value of counter=0
Value of counter=0
__________________________________________________________________________________
Chapter 8
Value of counter=0
print counter After increase value by a1 a2 and a3 objects
Value of counter=3
Value of counter=3
Value of counter=3
Static methods in Java can be called without creating an object of class. Static method doesn't
modify state of object. Static method mostly operates on arguments, almost all static method
accepts arguments, perform some calculation and return value.
Example1: Java static method and instance method called from same class
packagealpha;
publicclassDemoStatic
{
static void display()
{
System.out.println ("Static method Called.");
}
void show()
{
System.out.println ("Non static method Called.");
}
publicstaticvoid main(String[] args)
{
display(); //static method calling without object
DemoStatic a1 = new DemoStatic();
a1.show(); //non static method calling using object
}
}
Output:
Static method Called.
Non static method Called.
Example 2: Java static method and instance method called from different class.
packagealpha;
publicclassDemoStatic
{
staticvoiddisplay()
{
System.out.println ("Static method Called.");
}
void show()
{
System.out.println ("Non static method Called.");
}
}
__________________________________________________________________________________
Chapter 8
packagealpha;
publicclassClassB
{
publicstaticvoidmain(String[] args)
{
DemoStatic.display(); //static method call with class name
DemoStatic a1 = new DemoStatic();
a1.show(); //non static method calling using object
}
}
Output:
Static method Called.
Non static method Called.
3.16 Nested class (inner class) static inner-class and non-static inner class: [Nov dec
2011, June 2011]
In Java nested classes means one or more classes are defined inside another class.Java
developers refer to nested classes as inner classes, but inner classes have several different
types of nested classes such as static inner class, non-static inner class, local class and
Anonymous inner class.
Example:
public class OuterDemo
{
intb=20;
static class inner
{
int a=10;
public void innerMethod()
{
System.out.println("inner class method is called ");
}
}
publicstaticvoid main(String []args)
{
OuterDemo.inner obj=new OuterDemo.inner();
System.out.println("Value of a =" + obj.a);
obj.innerMethod();
//System.out.println(obj.b); cannot access; var b is declared in outer class
}
}
Output:
Value of a =10
inner class method is called
__________________________________________________________________________________
Chapter 8
Non-static nested classes in Java are also called inner classes. Inner classes are associated
with an instance of the enclosing class. Thus, you must first create an instance of the
enclosing class to create an instance of an inner class.
Notice how you put new after the reference to the outer class in order to create an instance of
the inner class
publicclass OuterDemo
{
publicvoid OuterclassMethod()
{
System.out.println("Outer class method is called "); }
class inner
{
__________________________________________________________________________________
Chapter 8
publicvoid InnerclassMethod()
{
System.out.println("inner class method is called ");
}
}
publicstaticvoid main(String []args)
{
OuterDemo obj =new OuterDemo();
obj.OuterclassMethod(); // call outer class method
OuterDemo.inner i =obj.new inner();
i.InnerclassMethod(); // call inner class method
}
}
Output:
Outer class method is called
inner class method is called
Example:
publicclass OuterClass
{
publicvoid display()
{
System.out.println("Outer class method display() called");
inner i=new inner();
i.show();
}
class inner
{
publicvoid show()
{
System.out.println("inner class method show() called");
}
}
publicstaticvoid main(String[] args)
{
OuterClass obj=new OuterClass();
obj.display();
}
}
Output:
Outer class method display() called
inner class method show() called
__________________________________________________________________________________