What is Java Constructor?

What is Java Constructor?

Java constructor plays a very important role in coding. Simply a constructor looks like method but is very different from method and purpose. Following tutorial gives complete authority over Java constructors. First let us know where exactly constructors fit in Java coding.

A constructor is that one which is called implicitly when an object is created in Java. A constructor gives properties to an object while it is being created itself. Else, separate methods are required to give properties to the object after it is created. Both styles are given hereunder.

Observe the code where properties for a Student object are given using a Java constructor at the time of object creation.

public Student(int marks, String name)

This is called constructor and will be discussed downside.

Through constructor, std1 object is given properties of marks and name (in Spring, it is known as constructor injection; injecting the properties to an object through constructor).

Let us repeat the same code with methods, say setter methods.

See how much code increases with methods. This is the importance of constructor in Java. In Java, String constructor is overloaded many folds and is discussed in Java String Constructors.

Java Constructor is a good concept and must be studied elaborately; should be known how to write a constructor, constructor overloading, calling same class constructor and super class constructor etc. and all are discussed very clearly with code examples in Constructors and Constructor overloading.

Other Constructor related Topics, Read only when you are comfortable with basic constructor examples

Leave a Reply

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