Showing posts with label constructors in java. Show all posts
Showing posts with label constructors in java. Show all posts

Tuesday, 2 February 2016

Constructors in Java

Java Constructors


               Constructors in Java is a special type of method that is used to initialize an object.

               In other words, Constructor in Java is a bit of code that allows you to create objects from a class. 'New' is the keyword used to call a constructor.

Constructors In Java

Rules for Constructors in Java


  1. Constructor name should match the name of the class it resides.
  2. Constructor must not have a return type. 
  3. If we do not manually include a constructor, a default constructor will be automatically generated by the compiler in Java. 
  4. Constructors invoked implicitly. i.e, invoked using the keyword 'new'.
  5. Constructors in Java cannot be abstract, static, final or synchronized. 

Example for Default Constructor


class DemoConstructor
{
     public DemoConstructor()
     {
         System.out.println("Default constructor");
     }
}

Example for Parameterized Constructor


class DemoConstructor
{
      public DemoConstructor(int num, String str)
      {
           System.out.println("Parameterized constructor");
      }
}