java constructor

Java Constructor

Java Constructor

  • Constructor is special member of class it is used to initialize data member of class at time of object creation.
  • Every class must have constructor either user define or compiler define(default constructor)
  • Constructor define by programmer is known user define constructor where as constructor define by compiler is known as default constructor.
  • If user not define constructor then compiler automatically define

There are two types of Java Constructor

  1. User define
  2. Compiler define
  • Constructor without any parameter is known as zero parameter or no argument constructor
  • Constructor define with parameter is known as parametarized constructor.
  • parametarized constructor used to pass value in constructor.
  • Constructor name same as class name
  • Constructor has no return type

Java constructor overloading

  •  In a class we can define any number of constructor is know as overloaded constructor.
  •  Whenever we create overloaded constructor argument should be differ in terms argument type or argument length.
  •  The overloaded constructor are used to create object with different initialization
  • Constructor returns the object address which is constructed by constructor of class.

 

Example of Overload Constructor and parametarized constructor

[pastacode lang=”java” manual=”%0Apackage%20constructor%3B%0Aclass%20Demo1%0A%20%7B%0A%09int%20a%3D10%3B%0A%09int%20k%3B%0A%09double%20d%3B%0A%09%0A%09%2F%2Fzero%20argument%20constructor%0A%09Demo1()%0A%09%7B%20%20%0A%09%09k%3D12%3B%0A%09%09d%3D12.4%3B%09%0A%09%7D%0A%09%2F%2F%20u%20can%20overload%20the%20constructor%0A%09%2F%2F%20but%20argument%20should%20differ%20in%20terms%20of%20argument%20%0A%20%20%20%20%20%20%20%20%2F%2F%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20type%20or%20length%20of%20argument%0A%09%0A%09%0A%09Demo1(int%20a)%20%2F%2FParameterized%20constructor%0A%09%7B%0A%09%09this.a%3Da%3B%0A%09%7D%0A%09%0A%20%7D%20%0A%0Apublic%20class%20Sample1%0A%7B%0A%09public%20static%20void%20main(String%5B%5D%20args)%0A%09%7B%0A%09%09System.out.println(%22*************************%22)%3B%0A%09%09%0A%09%09Demo1%20obj1%3Dnew%20Demo1()%3B%0A%09%09%0A%09%09System.out.println(%22k%20value%20%3A%20%22%2Bobj1.k)%3B%0A%09%0A%09%09System.out.println(%22d%20value%20%3A%22%2Bobj1.d)%3B%0A%09%09%0A%09%09Demo1%20obj2%3Dnew%20Demo1(12)%3B%0A%09%09%0A%20%20%20%20%20%20%20%20System.out.println(%22a%20value%20%3A%20%22%2Bobj2.a)%3B%0A%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%20%20%20System.out.println(%22*************************%22)%3B%0A%09%7D%0A%0A%7D%0A” message=”” highlight=”” provider=”manual”/]

output:

*************************
k value : 12
d value :12.4
a value : 12
*************************

 

Leave a Reply