Which class is super class of every class

What is Constructor

Answer : A constructor in a class is a special type of subroutine called to create an object. It prepares new object for use, often accepting arguments that the constructor uses to set member variables required. Below are some important point regarding constructor:

  • Constructors never have an explicit return type
  • Constructors cannot be directly invoked (the keyword “new” invokes them)
  • Constructors cannot be synchronized, final, abstract, native, or static
  • Java provides access to the superclass constructor through the super keyword

Java constructors perform the following tasks in the following order:

  • Initialize the class variables to default values. (byte, short, int, long, float, and double variables default to their respective zero values, booleans to false, chars to the null character (‘\u0000’) and object references to null.)
  • Call the default constructor of the superclass if no constructor is defined
  • Initialize member variables to the specified values
  • Executes the body of the constructor

Please see example below:

package com.javahonk.thistest;

public class ConstructorTest {

    // definition of the constructor.
    public ConstructorTest() {
	this(1);
    }

    // overloading a constructor
    public ConstructorTest(int input) {
	data = input; // This is an assignment
    }

    // declaration of instance variable(s).
    private int data;

}

 

Leave a Reply

Your email address will not be published. Required fields are marked *