Java Constructor

Java Constructor :

  • Constructor is used to construct an Object and initialize values
  • By default if no constructor is specified in the code then JVM supplies the constructor at run time.
  • The constructor is supplied by JVM is called default constructor.
  • If the developer doesn’t write the constructor explicitly then the JVM provides default constructor.
  • If your constructor is PRIVATE then the Object is created with in that class.
  • All four Access level modifiers are allowed, but non-access modifiers are not allowed.
  • The class name should be the constructor name.
  • this()constructor or super()constructor must be in the first line.
  • This() and super() cannot come together.
  • Super()constructor calls the super class constructor.
    • Example : super() ? calls the super class constructor with no arguments.
    • Super(1001,’mutn’) ? calls the super class constructor with two arguments.
  • This()constructor calls the constructor with in the same class.
    • Example: this() ? calls the empty constructor.
    • This(1001,’mutn’) ? calls the constructor  with two arguments in the same class.
  • Generally the execution of constructor occurs subclass constructor calls super class constructor, which calls it super class and so on.
  • Finally Object constructor executes and return to the calling constructor, which completes and return to its calling constructor and so on.
  • Constructor cannot be inherited.
  • Default constructor is stopped by JVM when you explicitly specify the constructor.
  • JVM explicitly adds super() keyword as the first line, if this() or super() keyword is not given explicitly.
  • Abstract class can also have constructor.