Java: Constructors

This tutorial explains the use and creation of constructors.

*A constructor is used as an example with serializable.

A constructor is a method with the same name as the class in which it is defined and is automatically called with the operator new.

CODE example:
public class Constructor{
public static class Objects implements{
String text;
public Objects(){
text = “William. §”;
public Objects(String s){
text = s;
public static void main(String args[]){
//create an object initialized by the constructor
Objects o = new Objects();
System.out.println(o.text); //the output is William. § since that is the text provided in the default constructor.
//create another object initialized with text supplied
Objects o2 = new Objects(“Wilson”);
System.out.println(o2.text); //the text within the object o2 is Wilson since we supplied it

This example uses two different constructors in the same class Objects. This is possible only because the parameter list is different for the two constructors and is possible for any method. Thus the JVM determines which instance of the method to call based on the variables involved. In our case, one involves no parameters, and the other has a String.
This is known as method or function Overloading, when applying the same name to different operations.

Constructors are very useful when default values are wanted to initialize a newly created Object.

Questions/Comments: [email protected]
-William. § (marvin_gohan)

Previous articleJava: Serializable
Next articleJava: toString


0 0 votes
Article Rating
Notify of
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

Cleveland Furia on How to Clear Google Activity
Sid Wohlfarth on How to Clear Google Activity
Riley Magsayo on How to Clear Google Activity
สมัครรับเครดิตฟรี ทันที on How to improve Remote Desktop Protocol Performance
Neal Wangstad on How to Clear Google Activity
Slavcho Andov on How to install Ubuntu
Slavcho Andov on How to fix bad sectors
Sheraz Ali on How to Backup Android
Would love your thoughts, please comment.x