Modal Box

Java Constructor

Constructor are the special functions which have the following properties :
  1. They have the same name as the class name.
  2 They do not have any return type, not even void.
  3. No need to call them automatically, called once when object is being created.
  4. Constructor may be default or parameterized as well.
  5. Mainly used to initialize the objects.

class TestClass
{
  TestClass() // this is constructor as it has the same name as class name.
   {
     System.out.println("This is default contructor");
   }
}

class check 
{
  public static void main(String args[])
   {
     TestClass obj= new TestClass(); //automatically constructor is being called.
   }
}
 Output: This is default constructor.

Similarly, parameterized constructor may also be used.

Empty constructor:

class EmptyConstExample
{
  EmptyConstExample() // this is by default and called once object is created.
   {
    }
  void display()
   {
      System.out.print("This function will print");
   }
}

class checkMain{
  public static void main(String args[])
   {
     EmptyConstExample obj= new EmptyConstExample(); // now empty constructor called 
     obj.display();
   }
}
 Output: This function will print

Video/ C Introduction

Watch video in full size
Wordpress Social Share Plugin powered by Ultimatelysocial