Previous | Home | Next |
Defining a Class
A class represent ADT(Abstract Data Type). it acts like a template using which we can create multiple objects. A class Declaration only create a template, it does not create an actual object. A class creates a new data type that can be used to create object. That is a class creates a logical framework that defines the relationship between its members. when we declare an object of a class, we are creating an instance of that class. Thus a class is a logical construct. An object has physically reality.
Example :
modifiers class <class-name> { modifier type variables; . . . . modifiers type methodName1(parameter-list) { <body of the method> } . . }
Declaring Objects
Student s1;
s1 is not an object. In c++ s1 will be treated as object but in java s1 is only a variable which can hold reference to an object of type student. This variable will hold garbage or null reference until we assign reference of some object of class student. It does not yet point to an actual object. Any attempt to use this variable at this point will result in a compile_time error. It is just like a pointer to an object in c/c++. If this variable is declared inside any block or a method then it is a local variable and will not be initialized to null, but if it is declared in a class then it will be an instance variable and will automatically be initialized to null.
Allocating Memory
In java memory is allocated dynamically with the help of new operator.
s1=new student();;
New operator will allocate memory for an object of class student and return its reference, which is then assigned to reference type variable s1. It will also call a default constructor to initialize member variables.
above two statements can be combined: student s1=new student();
note1:new allocates memory for an object during runtime. If new is unable to allocate memory (because memory is finite.) then it generate a run time exception/error
note2:if we assign a reference variable to another reference variable then only reference (address) will be transferred. There will not be any duplicate copy of the object. for example if we create another reference variable s2(student s2) and then (s1=s2). This will not create duplicate object, same object is referenced by s1 and s2. Any changes made in s2 will also be reflected in s1. No memory allocation is done with this assign. after a few steps if we assign null in s1 then that object will be destroyed by the garbage collector and the memory occupied by that object will be freed.
Previous | Home | Next |