There are three various types of constructors , and they are as follows:
1)Default Constructor – With no parameters.
2)Parametric Constructor – With Parameters. Create a new instance of a
class and also passing arguments simultaneously.
3)Copy Constructor – Which creates a new object as a copy of an existing
object.
A java constructor has the same name as the name of the class to which it
belongs. Constructor’s syntax does not include a return type, since constructors
never return a value.
Constructors may include parameters of various types. When the constructor is
invoked using the new operator, the types must match those that are specified in
the constructor definition.
Java provides a default constructor which takes no arguments and performs no
special actions or initializations, when no explicit constructors are provided.
The only action taken by the implicit default constructor is to call the
superclass constructor using the super() call. Constructor arguments provide you
with a way to provide parameters for the initialization of an object.
class vahical { string name; string model; car(); // constructor{ name =""' model =" " }} |
There are basically two rules defined for the
constructor.
a)Constructor name must be same as its class name
B)Constructor must have no explicit return type
Example of default constructor:
class car{ car() {System.out.println("car is created");} public static void main(String args[]){ car b=new car(); } } |
Example of parameterized constructor:
class Student{ int id; String name; Student(int i,String n){ //parameterized constructor id = i; name = n; } void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student s1 = new Student(1oo,"rita"); Student s2 = new Student(200,"Arzoo"); s1.display(); s2.display(); } } |
Example of copy constructor:
class Student{ int id; String name; Student(int i,String n){ //parameterized constructor id = i; name = n; } void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student(int i) //copy constructor Student s1 = new Student(1oo); Student s2 = new Student(1oo,"rita"); Student s3 = new Student(200,"Arzoo"); s1.display(); s2.display(); s3.display(); } } |