Java constructors

A constructor is a special method that has the same name as the class in which it exists and it is used to create an object of the class. To instantiate an object of the class Subscriber we use the following statement.

Subscriber subscriber = new Subscriber();

Some times there is no constructor defined in the class at all, but anyway you can use the above statement to instantiate objects. By default, every class has a no-argument constructor whether it exists inside the class or not. Constructor can be used to create an initial state for the object you want to instantiate.

 

public class Subscriber {

	Subscriber() { // A constructor of the class Subscriber
	}
}

 

When we use the statement Subscriber subscriber = new Subscriber(),  we actually use the default non-argument constructor. The constructor Subscriber() returns an object of the class Subscriber.

constructors-color

Defining a constructor

It is important to understand that the default constructor which is also a non-argument one exists only in classes that does not have any constructor. Once you define a constructor with one or more arguments, then you cannot use the default one to instantiate objects. See the example below:

 

Example 1:

Both classes Subscriber and Subscriber2 can use the no-argument constructor. In the class Subscriber2, there is no constructor at all, but that doesn’t matter. It can still use the statement

Subscriber2 sub = new Subscriber2();” to instantiate the object sub.

class Subscriber {

	String name = "Jack";

	Subscriber() {
	}
	public static void main(String[] args){
		Subscriber sub = new Subscriber();
		System.out.print(sub.name);
	}
}

class Subscriber2 {

	String name = "Emily";

	public static void main(String[] args){
		Subscriber2 sub = new Subscriber2();
		System.out.print(sub.name);
	}
}

 

Example 2:

The code below doesn’t allow to use a non-argument constructor, because a constructor with an argument is defined. The statement Subscriber sub = new Subscriber(); is not allowed.

If you want to instantiate the class below then you need to use the statement Subscriber sub = new Subsrcriber (“any string”);. To instantiate the class using the non-argument constructor, you need to define a second non-argument constructor.

class Subscriber {

	Subscriber(String name) {
	}
	public static void main(String[] args){
		Subscriber sub = new Subscriber(); // The constructor Subscriber() is undefined
		Subscriber sub2 = new Subscriber("Jack");
	}
}

 

Using the keyword “this”

In the body of a method, the “this” reference can be used like any other object reference to access members of the object.

 

Example 3:

in the following example, we pass the parameter name “Elvis” to both methods getName and getName2, but the result is that getName returns the name “Elvis” while getName2 returns the name “Jack” because we used the this reference, which refers to the instance variable.

class Subscriber {

	String name = "Jack";

	String getName(String name){
		return name;
	}
	String getName2(String name){
		return this.name;
	}
	public static void main(String[] args){

		Subscriber sub = new Subscriber();
		System.out.print("-" + sub.getName("Elvis"));
		System.out.print("-" + sub.getName2("Elvis"));
	}
}

 

Exercise 1

What happens when the following program is compiled and run?

class Subscriber {

	String name = "Bob";
	int age = 42;

	Subscriber(String nameSub, int age) {
		name = nameSub;
		age = this.age;
	}
	public static void main(String[] args){
		Subscriber sub = new Subscriber("Britney",33);
		System.out.print(sub.name + "-" + sub.age);
	}
}

Select the correct answer.


Exercise 2

What happens when the following program is compiled and run?

class Subscriber {

	String name = "Richard";
	int age = 28;

	Subscriber(int age) {
		this("Ben",30);
	}
	Subscriber(String name, int subAge) {
		name = this.name;
		age = subAge;
	}
	public static void main(String[] args){
		Subscriber sub = new Subscriber(33);
		System.out.print(sub.name + "-" + sub.age);
	}
}

Select the correct answer.


Please, leave your questions, feedback and suggestions in the comments below!
Sarmaroof.com offers a practical method to learn and improve your Java skills. It avoids unnecessary long boring theoretical explanations, but it uses many exercises and quizzes.

Sar Maroof's new book
Java quizmaster for beginners (English)

Java quizmaster voor beginners (Dutch)
Sar Maroof is the author of two Java books namely, Java quizmaster for beginners and A guide to build a Java application.
Experience with developing web applications since 2001
Sun Certified JSP as well as EJB
CIW Certified Internet Webmaster
Applied Science in Physics HBO Amsterdam
As well as Bachellor Science in Physics.
 Subscribe To sarmaroof RSS Feeds! (Your Browser)
 Mail This Page To A Friend!
 Bookmark This Page!
Share on FacebookTweet about this on TwitterShare on RedditShare on LinkedIn

5 Comments

Add a Comment
  1. Clear explanation and easy to understand.

  2. Awesome website keep up the good work

  3. Just do me a favor and keep writing such trnchnaet analyses, OK?

  4. Hi, Your content and the exercises are clear to understand. I learn so much from your website, thanks!

    1. A perfect reply! Thanks for taking the troblue.

Leave a Reply

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

Sarmaroof © 2017