Java Core – Java Constructor

How to initialize the state of Java object?

The tutorial will introduce Java Constructor for resolving above question.

I. What is Java Constructor?

– Constructor is a way to initialize the state of Java object at the creating time.
– Java has 2 type of constructor: no-argument constructor & argument constructor.

no-argument constructor

When executing, result

Argument Constructor

When executing, result:

– Creating a constructor for Java class is Not mandatory. If a class does Not define a constructor, Java compiler will use default constructor for initial the state for object. The default constructor of a Java class is no-argument constructor.

default constructor

– Result executing:

II. How to create a Java constructor?

– Java constructor has the same name with Java class, and No return value.
– Java constructor can be defined with public member’access or private, protected member’access.

Private or Protected member access is used in case for creating Singleton Pattern.

III. Default Java Constructor

As above information, the default constructor of a Java class is no-argument constructor.
Java will use the no-argument constructor of superclass if the class has explicit superclass. If class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor.


When executing, result:

IV. Difference between Constructor and Method

– Constructor is used to initialize object, but method is used to expose behaviour of object.
– Constructor is not having return-type, But method must have return-type.

By grokonez | October 4, 2016.

Last updated on June 4, 2017.

Related Posts

Got Something To Say:

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