Friday, November 17, 2017

Constructor in Java With Example

  • A constructor instates a protest when it is made. 
  • Constructor name must be same as the class name
  • The constructor must have no explicit return types
  • It has an indistinguishable name from its class and is grammatically like a technique.
  • Constructors have no express return sort. 
  • The constructor is used to give beginning esteems to the occurrence factors characterized by the class, or to play out some other startup methods required to make a full grown question. 

Types of Constructor in Java


Constructor in Java With Example

  • Default Constructor in Java:-

A constructor that has no parameter is known as the default constructor
class my2
{
             int x;
             // Following is the constructor
             my2()
            {
                    x = 50;
             }
}
class my1
{
              public static void main(String args[])
             {
                   my2 m = new my2();
                   System.out.println(m.x);
              }
}
Output:
50

  • The parameterized constructor in Java:-

A constructor that have parameters is known as parameter constructor.
class my2
{
            int x,y;
            my2(int i,int j)
           {
                     x = i;
                     y = j;
            }
}
class my1
{
            public static void main(String args[])
           {
                my2 m = new my2(40,10);
                System.out.println(m.x+m.y);
            }
}
Output:
50

  • Constructor Overloading in Java:-

Constructor over-burdening is a procedure in Java in which a class can have any number of constructors that contrast in parameter records. The compiler separates these constructors by considering the quantity parameters in the rundown and their sort.
class my
{  
          int id;  
          String name;  
          int age;  
          my(int i,String n)
         {  
                  id = i;  
                  name = n;  
         }  
        my(int i,String n,int a)
        {  
                  id = i;  
                  name = n;  
                  age=a;  
         }  
        void disp()
         {
                  System.out.println(id+" "+name+" "+age);
         }  
         public static void main(String args[])
         {  
                 my m1 = new my(101,"Dhiren",20);  
                 my m2 = new my(102,"Bhavesh",25);  
                 m1.disp();  
                 m2.disp();  
          }  
}  
Output:
101 Dhiren     20
102 Bhavesh  25


No comments:

Post a Comment

Top 200+ Core Java Interview Questions And Answers For 2019

Most Popular Java Interview Questions Given below is a comprehensive list of most important and commonly asked basic and advanced Java p...