Programming Language (JAVA) : Unit 6.6 - Classes and Objects
Programming Language (JAVA) : Unit 6.6 - Classes and Objects
Presentation 2
Objectives
At the end of this presentation, you will be able to: Use constructors to initialize data members
Constructors
Is a special method that enables an object to initialise itself when it is created.
Constructors
Characteristics of Constructors Constructors have the same name as the class name. They do not return any value. The syntax of a constructor is similar to that of a method. Once defined the constructor is automatically called immediately when the object is created before the new operator completes its job. Java creates a default constructor when you do not define a constructor.
Example - Constructor
class Book { Book(String bname, String aname, int nopages) { book_name = bname; author_name = aname; no_of_pages = nopages; } public static void main(String args[]) { Book b1 = new Book ("Java 2","Herbert Schildt",100); } }
Hands-On!
Program Book1.java illustrates the use of constructor in a class.
Constructor
Lab Exercise
1. Create a class named Person. It should have instance variables to record name, age and salary. These should be of types String, int, and float. Use the new operator to create a person object. Create a constructor inside the class to initialize instance variables. In the main method pass values while creating object. Display the values using the displayData( ) method.
Lab Exercise
2. Create a class named bank_account. It should have instance variables to record the name of the depositor, account number, type of account and balance amount in the account. These should be of types String, float, String and float, respectively. Create a constructor inside the class to initialise instance variables. In the main method, while creating objects pass values. Display the values using displayData( ) method. Display the name and balance using displayData( ) method.
Summary
In this session, you learnt the following: A constructor is a method that enables an object to initialize itself when it is created.