Constructor
Constructor
name is same name as that of class name
It does
not have any return type
It can
be overloaded
It is
called when object is created.
By
default default constructor is called when object is created
It is
used to initialize the instance variable of an object
Types:
There
are two types of constructor in java
1)
Default constructor (No arguments)
2)
Parameterized constructor (Having argument)
Default
constructor
public class A {
public A() //default constructor
{
System.out.println("default
constructor");
}
public
static void main(String[] args)
{
A
a1=new A(); //constructor is called
when object is created
}
}
Output:
default constructor
Parameterized constructor
public class A{
public A( int
a,int b) //parameterized constructor
{
System.out.println("sum
is:"+(a+b));
}
public
static void main(String[] args)
{
A
a1=new A(55,67); //constructor is called
when object is created
}
}
Output:
sum is:122
constructor (constructor is
used to initialize instance variable of an object)
public class A{
int x,y;
public A( int
a,int b)
{
x=a;
y=b;
System.out.println("sum is:"+(x+y));
}
public
static void main(String[] args)
{
A
a1=new A(55,67);
}
}
Output:
sum is:122
Constructor (Using method)
public class A{
int x,y;
public A( int
a,int b)
{
x=a;
y=b;
}
void show()
{
System.out.println("sum
is:"+(x+y));
}
public
static void main(String[] args)
{
A
a1=new A(55,67);
a1.show();
}
}
Output:
sum is:122
Constructor(Constructor can
be overloaded)
public class A
{
int x,y;
public A(int a)
{
x=a;
System.out.println("Value is "+x);
}
public A( int
a,int b)
{
x=a;
y=b;
System.out.println("sum is:"+(x+y));
}
public
static void main(String[] args)
{
A a1=new A(78);
A a2=new A(55,67);
}
}
Output:
Value is 78
sum is:122
Constructor (using this
keyword)
public class A
{
int x,y;
public A( int
x,int y)
{
this. x=x;
this. y=y;
}
void show()
{
System.out.println("sum is:"+(x+y));
}
public static void main(String[] args)
{
A a2=new A(55,67);
a2.show();
}
}
Output:
sum is:122
No comments:
Post a Comment