concept of constructor

Constructor is a special type of method that is invoked at the time of object creation. It is used to initialized the object.

RULE :
1) Its name must be same as class name.
2) It must not have any explicit return type.

TYPE

  • Default
  • Parameterized
Default Constructor :
A constructor that have no parameter is known as
default constructor.

class Bike{
Bike(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike b=new Bike();
}



Output: Bike is created

Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

Parameterized constructor :
A constructor that have parameter is known as parameterized constructor.

Parameterized constructor is used to provide different values to the distinct objects.

In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor.

class Student{
    int id;
    String name;
    
    Student(int i,String n){
    id = i;
    name = n;
    }
    void display(){System.out.println(id+" "+name);}

    public static void main(String args[]){
    Student s1 = new Student(111,"Karan");
    Student s2 = new Student(222,"Aryan");
    s1.display();
    s2.display();
   }
}





Output : 111 Karan
        222 Aryan


                    JAVA TUTORIALS HOMEPAGE




0 comments:

Related Posts Plugin for WordPress, Blogger...
Copyright © 2013 futureX | Blogger Template by Clairvo