Constructor in java
Constructor is also know as the methid or the function in the java .Constructor are mainly used in the java programs to create the object of the class.
Exmple:-
class Employee
{
public void setData()
{
System.out.println("This is the class Method");
}
public static void main(String args[])
{
Employee e=new Employee();
e.setyData();
}
}
In this program we can clearly see that we have constructe the object of the Employee class witn the hep of the new keyword.Normally cinstruction of the cklas means the allocating the memory space this reference.Refernce is the another topic we will disscuss deeply about this in another post.
See some impoetant points of the constructor
- The constructor is same like the fucntions or the methods used in the progerams.
- constructor name should be same as the name of the class.
- The cionstructor having no return types
- Constructors can use the public access specifiers
- We can use the constructors in the abstract class but can't instatiate using thid.But we can instatiate the concrete class.
Types of Constructors in java:-
There are two types of constructors in the java.
1.Default constructor
2.non parametrised constructor
3.parametrised constructors
Default constructor
If we are not defining any constructors in the program then at the time of construction of the object the default constructor will be called.
Non parameterised constrcutors:-
In the non parametirsed constructors we are not passing any arguments and the main point is that the at the time of the execution of the JVM call the non parameterised constructor.
Parameterised constructor:-
It is the opposite of the non parameterised constrcutor.
See some xemple
Example1:-
class Demo1
{
int data;
Demo1()
{
data++;
System.out.println("Object is constructed");
}
protected Demo1(int x)
{
data=x;
}
public static void main(String args[])
{
Demo1 dd=new Demo1();
Demo1 bb=new Demo1(12);
System.out.println("value of the first object is"+dd.data);
System.out.println("Value of the second object is"+bb.data);
}
}
Example2:-
class Demo2
{
int data;
Demo2()
{
data++;
System.out.println("the object is constructed");
}
public void increment()
{
data++;
}
public static void main(String arg[])
{
Demo2 dd=new Demo2();
dd.increment();
dd.increment();
dd.increment();
dd.increment();
dd.increment();
System.out.println("the data Value is"+dd.data);
}
}
keep pratice this programs and try to get the out put.
next:-Use of this keyword(click here)


No comments:
Post a Comment