Constructor in Java
Constructor is one of the distinguish programming functions in Java programming.The purpose of constructor is to "Initialize the object."
Definition
A constructor is one of the special member method which it is automatically implicit called by JVM during the object creation and whose role is to place your own values without placing default values.
Advantages of constructor
When we use constructor at the time of writing Java application then we get following advantages.
1) It eliminates in placing default values.
2) It eliminates in calling ordinary methods.
Characters of constructor
If we want to use a constructor as a part of Java program then we have follow properties.
1) Constructor will be called by the JVM implicitly when the object is created.
2) Constructor name is most similar to class name.
3) Constructor will not have any return type even void also ( if we write any return type then it will be treated as "Ordinary Method".)
4) Constructor should not be static ( because of constructor calling each & every time when an object is created ).
5) Constructor of java never participates in inheritance process (Because every constructor is meant for initializing with their own data member but not data member of another class.
6)
a)If the access modifier of the constructor is private then an object of an corresponding class can be created in the class context but not in other class context.
a)If the access modifier of the constructor is private then an object of an corresponding class can be created in the class context but not in other class context.
b) If the access modifier of the constructor not private then an object of the corresponding class can
be created both class context and in another class context.
Syntax
class ClassName
{
------------
<ClassName>(Default Constructor)
{
Block Of Statement 's
}
}
Type Of Constructor
In Java programming we have two types of constructors. They are :
1) Default /Parameter less /Zero argument constructor
2) Parameter constructor
Default Constructor
The purpose of default constructor is that to create multiple object with respect to same class for planing "same values".
Definition
A constructor is said to be default constructor if and only if it does not take any parameters values.
class ClassName
{
------------
<ClassName>(Default Constructor)
{
Block Of Statement 's
}
}
Q. Write a java program which illustrate a concept of default constructor
Program :-
class Text
{
int a,b;
test( )
{
System.out.println("test -Default Constructor");
a=100;
b=200;
System.out.println("val of a="+a);
System.out.println("val of b="+b);
}
}//test
Class TextDemo
{
public static void main(String args{})
{
Test t1=new Test(); //100,200
Test t2=new Test(); // 100,200
}
}
{
public static void main(String args{})
{
Test t1=new Test(); //100,200
Test t2=new Test(); // 100,200
}
}
No comments:
Post a Comment
Thanks for visiting my site..