Unit-8 Constructors in java

Types of Constructors in java

Example : Person

import java.io.*;
class Person
{
String name;
int age;
Person()
{
name="Unknown";
age=0;
}
Person(String n,int a)

{
name=n;
age=a;
}
void show()
{
System.out.println("Name:"+name+",Age:"+age);
}
public static void main(String args[])
{
Person P;
P=new Person();
P.show();
P=new Person("Babu",35);
P.show();
}
}
Output : Person

Example : Point

import java.io.*;
class Point{
int x,y;
Point(int x,int y)
{
this.x=x;
this.y=y;
}
void display()
{
System.out.println("x="+x+"y="+y);
}
public static void main(String args[])
{
Point pp=new Point(10,20);
pp.display();
}
}
Output : Point

Overloading Constructors in java…

Example : ConsOverload

import java.io.*;
class Box
{
double width,height,depth;
Box(double w,double h,double d)
{
width=w;
height=h;
depth=d;
}
Box()
{
width=-1;
height=-1;
depth=-1;
}
Box(double len)
{
this(len,len,len);
}
void Volume()
{
System.out.println("Volume:"+width*height*depth);
}
}
class ConsOverload
{
public static void main(String args[])
{
Box mybox1=new Box(10,20,15);
Box mybox2=new Box();
Box mycube=new Box(7);
mybox1.Volume();
mybox2.Volume();
mycube.Volume();
}
}
Output : ConsOverload

Passing objects to constructors in java…

Example : ConsOverload5

import java.io.*;
class Box
{
double width,height,depth;
Box(double w,double h,double d)
{
width=w;
height=h;
depth=d;
}
Box(Box ob)
{
width=ob.width;
height=ob.height;
depth=ob.depth;
}
void volume()
{
System.out.println("Volume:"+width*height*depth);
}
}
class ConsOverload5
{
public static void main(String args[])
{
Box mybox1=new Box(10,20,15);
Box mybox2=new Box(mybox1);
mybox1.volume();
mybox2.volume();
}
}
Output: ConsOverload5

Static Variable in java…

Example : Rect

import java.io.*;
class Rect
{
int length;
int breadth;
static  int count;
Rect()
{
count++;
}
static 
{
count=0;
System.out.println("Inside static block");
}
public static void main(String args[])
{
System.out.println("No of objects:"+Rect.count);
Rect r1,r2;
r1=new Rect();
System.out.println("No of objects:"+r1.count);
r2=new Rect();
System.out.println("No of objects:"+Rect.count);
}
}
Output : Rect

Static Methods in java…

Example : Rect5

import java.io.*;
class Rect5
{
int length;
int breadth;
static int count;
Rect5()
{
count++;
}
static
{
count=0;
System.out.println("Inside static block");
}
static void displayCount()
{
System.out.println("No of object:"+count);
}
public static void main(String args[])
{
Rect5 r1,r2;
Rect5.displayCount();
r1=new Rect5();
r1.displayCount();
r2=new Rect5();
r2.displayCount();
Rect5.displayCount();
}
}
Output : Rect5