Search This Blog

save java programs with".java" extension

examples :

helloworld.java
sample.java
match.java
send-mail.java

quick links

Showing posts with label constructor. Show all posts
Showing posts with label constructor. Show all posts

constructor overloading in java

class rectangle
{
int l,b;
rectangle()
{
System.out.println("\nrectangle()");
l=10;
b=20;
}
rectangle(int x)
{
System.out.println("\nrectangle(int x)");
l=x;
b=x;
}

rectangle(int x, int y)
{
System.out.println("\nrectangle(int x , int y)");
l=x;
b=y;
}
void area()
{

System.out.println("area :"+(l*b));
}
}
class constuctordemo3
{
public static void main(String args[])
{
rectangle r1= new rectangle(5,15);
rectangle r2= new rectangle();
rectangle r3= new rectangle(100);
System.out.println("\n\narea() with r1");
r1.area();
System.out.println("\n\narea() with r2");
r2.area();
System.out.println("\n\narea() with r3");
r3.area();
rectangle r4=r1;             //here address of r1 copied to address r4
System.out.println("\n\narea() with r4");
r4.area();
rectangle r5=r3; //here address of r3 copied to address r5
System.out.println("\n\narea() with r5");
r5.area();
}
}

parameterized constructor in java

class square
{
int l;
square(int x)
{
System.out.println("inside constructor of square");
l=x;
}
void area()
{
System.out.println("area of square :"+(l*l));
}
}
class demo
{
public static void main(String args[])
{
square s1= new square(10);
s1.area();
square s2= new square(20);
s2.area();
square s3= new square(30);
s3.area();
}
}

==================================================
output :
inside constructor of square
 area of square :100
inside constructor of square
 area of square :400
inside constructor of square

 area of square :900

default constructor in java

class square
{
int l;
square()
{
System.out.println("inside constructor of square");
l=10;
}
void area()
{
System.out.println("area of square :"+(l*l));
}
}
class defaultconstructordemo1
{
public static void main(String args[])
{
square s = new square();
s.area();
}
}
=================================================
output :

inside constructor of square
 area of square :100