Home » Online Computer Education » Learn Fundamentals of Java Programming “Constructors in Java Programming ” Lesson 19

Learn Fundamentals of Java Programming “Constructors in Java Programming ” Lesson 19

Constructors

A data member that is declared but not initialized before using, is assigned a default value by the compiler usually either zero or null. However, it is good programming practice to always initialize variables before using them.

A special method member called the constructor method is used to initialize the data members of the class (or any other initialization is to be done at time of object creation). The constructor has the same name as the class, has no return type, and may or may not have a parameter list. Whenever a new object of a class is created, the constructor of the class is invoked automatically. We do not call the constructor explicitly.

Let us define a constructor for the Book class that takes parameters corresponding to each data member and uses the parameters to initialize the data members (Figure 1.8f).

Java fundamentals  array 9

We can now use our constructor to create an object of the Book class.

Book book1 = new Book(“Game of Thrones”,
“George R Martin”,
“Harper Collins”,
“Fiction”, 450.0);

This has the effect of creating a new object book1 with its data members set as per the parameter list of the constructor.

Note that once we have defined a parameterized constructor, we will not be able to create a Book object without any parameters, that is, with a statement like:

Book book3 = new Book();

The compiler will complain that the methods actual and formal arguments differ in length. If you want to still be able to create a book object without specifying any parameters, you will have to also define a parameter-less constructor as below.

Book() {
title = “”;
author = “”;
publisher = “”;
genre = “”;
price = 0 ;
}

The parameter-less constructor above initializes all the data members of the book with default values (null string in case of String parameters and 0 for the double parameter).

About

The main objective of this website is to provide quality study material to all students (from 1st to 12th class of any board) irrespective of their background as our motto is “Education for Everyone”. It is also a very good platform for teachers who want to share their valuable knowledge.

Leave a Reply

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