A class is the blueprint from which individual objects are created.
Consider an address book. Each page has the same blank fields(name, address, cell, fax, e-mail....). We can call these blank fields instance variables of the class AddressBook. When you fill out a page you are creating an instance(object). Each object made from the class can have its own values for the instance variables of the class. The method of a class are the things that you do to a particular page. For eg: setName(), changeName(), getName(), setAddress(), ......
How do we create an object?
To create objects in java, you must use the keyword new. At the same time an object is created, you need to store a reference to it in a variable of suitable type—that is, the same type as the class.
For eg: You must have contacts of many people in your phone. You can use the contact to call a person. The person is actually somewhere else but you can use the contact number in your phone to call them. You can think of a Reference variable to be a contact and Object to be the actual person you are calling
AddressBook ab= new AddressBook();
Here ab is a reference to this object; it’s not the object itself. The memory location ab does not hold the data of a AddressBook object. Instead, it contains the memory address of a AddressBook object that is actually stored elsewhere in memory.
Consider,
AddressBook ab;
In this case, ab won’t hold a reference if it has not been assigned an object at some prior point in the program. Before being assigned an object, it holds a reference to a special object called null.
Creating an object is also called instantiating it, and an object is often referred to as an instance of a class
No comments:
Post a Comment