3- Object Creation



This is done by using the new operator   ‘new’ is a key word in java.
An important responsibility of new operator is to transfer the contents of a .class file from the hard disk into the RAM.




Example:
public class A    {
             int i=1; 
             int j=2;
Public static void main(String[] args){
                  A a1 = new A();
                 a1.i =10;
                a1.j =20;
              A a2 = new A();
              a2.i =1;
             a2.j =2;     }      } 











 

Note: -   In a given code all the elements that have the keyword ‘static’. Before them are known as
             Static elements.  Others are known as   non static’.
A a1 = new A();
Consider the above programme when ever this programme is compiled and executed first the main() method is transferred from the hard disk to the RAM.
The first statement inside the main method is    
As soon as the keyword new is encountered by the JvM it understands that it has to load all the non static elements of the .class file from hard disk to the RAM. Inside the RAM some memory space would be allocated for these non-static elements and the address of the memory location would be assigned to the variable a1, where a1 is a variable of type class A.
For example when we have a statement a1.i then it gets access to the content of a1 which is nothing but the address of the memory location where the variable ‘i’ is stored. Now it can get access to the variable ‘i’ in that memory location whose address is in a1.
Ex: - a1.I =10;   a1.j = 20   etc...

“ Object ”  Definition: - 

The memory in the RAM which is reserved for the non static elements of the .class file is known as Object.
Ø The Concept of reserving memory in the RAM dynamically (i.e. at runtime) for the contents of hard disk is known as instance.
Ø Note that in case of the object, the memory is reserved for the contents of .class file (infact they are also contents of hard disk in the RAM )
Ø Hence the object is called as instance of a class.
Ø Now we can say that a1 is a variable which contains the address of the object. a1 is known as handler or pointer of the type A.
Note: - when we write a1.i =10, a1.j =20, then the values of a1.i and a2.j change to 10 & 20 respectively only
         in he RAM, but the values of I and j are not affected in the .class file i.e. A.class which is in the Hard disk.
NOTE:-
Since a1 points to an object of class A. many people call a1 as an object but strictly speaking a1 is not an object it is the reference of an object.(pointing finger ->TV ; Example. )
**..  Once the control comes out from the main (), then the main method is deleted from the Ram since the variables variables a1 and a2 are created in main, automatically they will also be deleted when main is deleted.
**.. So when a1 and a2 are deleted, the addresses to the objects pointed out by a1 and a2 are also lost.
Now these objects which have no variable to point them are treated as garbage.
In java it is the duty of the Garbage collector to clear this garbage. And free the memory in the RAM.





       In the above program as soon as it is compiled and executed, first main method is loaded into the RAM.  inside the main method , when the statement  Obj1 o = new Obj1(); is executed  the JVM loads all the non-static contents of the class Obj1 into the RAM from the hard disk and allocates memory for these non-static elements  and assigns the address of this  memory to the variable  o . Hence the object of class Obj1 is said to be created.
The non-static members are int i=0; j=0; and void fun1 () {----}, and void fun2 () {----------}
·        But here we have to note that JVM loads only the signatures and addresses of fun1 and fun2 into the RAM, instead of loading the entire body of the function.
·        We have to keep in mind that JVM follows the concept of dynamic loading.
Thus when the fun1() and fun2() are specifically  called , then the body of those functions will be loaded to the AM from the hard disk and once when the control comes out of the function , the body of the function will be deleted from the RAM. But the address of the function (ie  ... address of its location in the hard disk) will be present in the object.





Illustrated this information in the diagram.
Suppose if  i = i+1;    is a statement in fun1()  then the control finds out whether  I  is defined  fun1() or not  in this case , since it is not defined in fun1(),  the control goes to the object which available to function 1() using the address of the object present in the variable   ‘o’ and then searches for  ‘i’ now it finds I here  , suppose if it does not find the variable   ‘i’  declared here then it generates a runtime error.
From this it is clear that in order to execute fun1 (), we need to create an object of the class which holds fun1 (),
Hence without creating an object of the class we cannot execute the functions of that class.
è Signature and address of a function is also data hence object is said to be contain only data and nothing other than that.
è The data present inside the object is always tentative as and when we execute any functionalities acting on that data.
State of the Object:-
The data present inside the object at that particular instance of time is called “ State of the Object “.

Behaviour of the Object:-
The functionalities that are applicable to the object is known as Behaviour of the object. Variables ‘i’ and ‘j’ would be transferred to the Instance of the class (Object)
That is they are accommodated inside the instance and hence they are known as instance variables.
Any non static variable will be accommodated inside the instance and hence it is known as instance variable.
Local variables are those that are defined inside a function and their scope lies only within that function.
Example:-
class   Obj2   {
           int I =0;
           static int j =0;
      void fun1 ( )   {
         int I =0;
         I =25;
         J =35;
       S.o.p (“Inside func1 ()”);
       S.o.p (i);
       S.o.p (j);
      S.o.p (“end of fun1 ( )”);         }
public static void main (String args[])  {
Obj2     o   = new Obj2 ();
o.fun1 ();
S.o.p (o.i);
S.o.p (o.j);           }           }

Save the above programme as  Obj2.java
D:> javac Obj2.java
D:\> java Obj2

Output:-
Inside fun1()
25                                  à  i
35                                   à j
End of fun1()
     25                                     à I
     35                                     à  j


Interpretation of the output of the above program is as follows.
As the programme is compiled and executed ,  object  o will be created and after that fun1() is called using object  o. inside fun1()  we have int I =0; I = 25 ; j = 35 .
Here ‘I ‘is declared once again, so any value of ‘i’ will be local to this function.  so  now we have int I = 0;  so now ‘I’ is 25 ,  the next statement  j =35  , but j is not a variable of fun1()  , in fact it is a class variable   so j = 35 both inside the function and outside the function.
So after the execution of S.O.P statements we have I =25 and j = 35 and then control returns to main.  Now in main the next statement is   S.O.P(o.i );   S.O.P(o.j);  now I and j refers to the class variables  now the value of I is   ‘0’ and the value of j is 35 . because  ‘I’ is re-declared in fun1() and ay change in the value of   ‘I’  confined to a fun1()  once the control comes out of it, again the value of  ‘I ‘ will be  ‘0‘  but j is affected as it is accessed through  the object .
Hence the value of I is   0 and j   is 35.
NOTE: - Local variables have the highest priority at the time of execution   i.e.  if the control encounters a variable assignment , then it checks whether that variable is defined inside that function  or not. If Yes it is a local variable and it has its priority   if no, then the control goes to the object on which the function is acting to find the variable defined even if the variable is not defined inside the object. Then it generates a runtime error.

Comment Lines: - This is literally asking the compiler not to convert that statement (Having the comment lines into its equivalent executable code.
Compile the following two programmes with in the same path.
X.java

class   X           {
int I =0 ;
Void funx()      {
I = i+1 ;
I = i* I ;          }
public static void main(String args[])
{
X   x1 =  new X();
X1.i = 2 ;
X1.funx();
S.o.p(x1.i);

}          }

Obj2.java

class   Obj2    {
int j =1 ;

void fun1()      {
J = j +1 ;
X x1  = new X();
X1.i =15;
S.O.P(x1.i);        }
public static void main(String args[])     {
Obj2 o = new Obj2();
o.fun1();
X x1 = new X();
S.o.p(x1.i);  // here x1.i = 0

}          }

NOTE  :-  When a  ‘new ‘ operator is encountered  immediately  JVM loads all the non static members of a class into the RAM , and allocates some memory  and address of that  object is assigned to a variable of that class type.

The above two programmes get executed perfectly .we can observe that object of the X.class file is created inside Obj2.class file. Here one precaution is that we should take is the path of the execution of the two programs should be same.
Now we can conclude Object of any   .class file can be created at anywhere. (I.e. Inside any other program) provided the path should e same for both the programs.
Consider the following programme.
class   Obj3
{
. int x =1, j =2;
void fun1()
{
S.o.p(i);
S.o.p(j);
}
}
Save this program as Obj3.java

If we compile the above program it gets compiled and   even   .class file   Obj3.class will be created.
If we try to execute this program it will generate a runtime error. Because it does not have a main method.
Note: - Every .java file need not have a main method
è The main() method is required  inside the .class file  only to execute  that particular .class file
Because execution starts from the main method.
è There is no compulsion that every .class file should have some variables and functions inside it (or) at least one function in it.
è A class can be completely empty. Without any single statement inside it.

class   Xyz
{
// no statements inside it.
}





If we create the object of class Xyz, then an object will be created.
Since the class is empty without a single statement   in it. Object will also be empty.
But still remember that the object will have some properties inside it. (Discussed later.)
class   Demo1         {
. int x =0  ;
void funD()         {
x=10;
Demo1 d = new Demo1();
d.x =114;
S.o.p(d.x);   S.o.p(x);
S.o.p(“end of fund()"
}
public static void main(String args[])        {
Demo1 d1 = new Demo1();
d1.funD();
S.o.p(d1.x);
}          }

Save this program as Demo1.java

As soon as Demo1.class file comes for execution, the main method is loaded into the RAM, and it gets executed the first statement inside the main method creates an object of Demo1.class file and loads all the non static members of the class (ie. int x =0; signature and address of FunD ()) and the address of the object assigned to the variable d1.
Second statement is d.funD (); which is a call to the funD ()   now the fund () will loaded into the RAM
The first statement inside the fund() is  x =10   , as variable x is not defined inside the function it is automatically the x is inside the object on which the function is acting gets affected and now its value is  x =10 .
In the second statement we are again creating an object of Demo1.class file. So once again all the non static contents of the Demo1.class file are loaded into the RAM and the object is created whose address is assigned.
The next statement is d.x = 114; it assigns the value 115 to the variable x inside the object that was just created.  Now S.o.p (d.x);   prints 114. But S.o.p(x); prints 10.
After this the control comes out of the function and reaches the main method in this process fund () is deleted from the RAM and all the local variables of fund () lose their life. Now in the main method S.o.p (d.x); prints   10 as that is the value of x   inside the object.
class  DemoA      {
int I =o;
void funA()           {
S.o.p(“inside the function A of class DemoA”)
}      }

class DemoB       {
int j =0;
void funB()       {
S.o.p(“inside funB of Class DemoB”);
}    }

class DemoC       {
void function()      {
S.o.p(“inside func() of class DemoC”);
}
public static void main(String args[])  {
DemoA da = new DemoA();
DemoB db = new DemoB();
Da.funA();
Db.funB();
}         }

Save the above program as Democ.java

In the above program we have DemoA DemoB and DemoC classes.
When we compile the above program using     javac DemoC.java,   the compiler converts all the contents of the source file into its equivalent byte code.  So, when we compile the source file its equivalent .class file is created.     Till now  we have considered  program that  had only single class  along with the main method  but In this program , we have three classes  now what does the compiler do . ?
NOTE: - the java compiler converts all the contents of source file into their equivalent byte code.   Class wise.
In the above program, the compiler generates three   .class files    as there are three classes in the   source file   DemoC.java.
D:\> javac   DemoC.java
DemoC.class, DemoA.class, DemoB.class.
NOTE: - a .class file will always be an equivalent of only one class in the source file. The name of the .class file would be always the name of the class that particular “.class” file is representing.
To be more clear let us assume that we save the file DemoC.java as Pro1.java, we do not get any Pro1.class file and infact we get the .class file according to the classes present in the Pro1.java
Suppose, if we want to execute Pro1.java we have to use any of the .class files (that contains main method) that have been generated after compiling Pro1.java
NOTE: -    if we save the source file with the name of the class that has a main method then we can compile and execute the source file with the same name.  (As that of the class) this is the reason why people prefer to save the source file with the same name of the class.
Actually we can save the file with any name   we like but   to execute the .class file we have to supply that the .class file to the JVM which has the main method of it.
      Save the below program as Pro2.java   we have three classes DemoX, DemoY,    DemoZ   and each class has a main method   in one of those classes    we know that when we compile a .java file, the compiler creates .class files    for all the classes in the .java file but we are supposed to execute only one .class file at a time   i.e. For example   in the below program Pro2.java
D:\>   javac Pro2.java               à DemoX.class,   DemoY.class   and   DemoZ.class
D:\>   java   DemoX           D:\>   java   DemoY        or    D:\>   java   DemoZ
Hence at any instance   JVM can execute only one     .class   file it cannot execute two or more. Class files    simultaneously. On this program   or till now, we have seen programs with only one main method in one class.
class  DemoX    {
int I =0;
public static void main(string args[])   {
DemoY dy = new DemoY();
S.o.p(“ dy.j ”+dy.j);
Dy.funY();
}    }

class DemoY   {
int j =10;
public static void main(string args[])   {
DemoZ   z = new DemoZ();
z.funZ();     }
void funY()     {
S.o.p(“Inside FunY of  DemoY”);  }   }




class DemoZ    {
void funZ()     {
S.o.p(“inside func() of class DemoZ”);
}
uublic static void main(String args[])   {
DemoX dX = new DemoX();
Sop(dx.i);
}     }

Save the above file   As      Pro2.java



Note: - We can define more than one main method inside the same class with different arguments    i.e.
    P.S.V.M (String args [] );    
    P.S.V.M (int args [] );        etc...  This concept of polymorphism to be discussed later.

class   Obj6     {
                 Int I =1;
void function1 ()        {
                  I = i+1;
                  S.o.p (i);
                 S.o.p (“end of function 1”);     }
public static void main (String args [])     {
Obj6   O1 = new Obj6 ();
Int x1= 10;
O1.i = 25;
O1 = ne Obj6 ();
S.O.P (O1.i);                //   I =1
O1.i =16;
Obj6  O2 = O1;
S.O.P (O2.i);                 // o2.i = 16
}     }

In the above program we have changed the address stored in the reference and also we have created two references   to the same object.
Let us trace the program \
Assume that the main method is loaded into the RAM.  The first statement inside the main method is creation of an object so an object is created and its address is assigned to o1   . Now we have int x1 =10;
So a variable x1 is assigned a value of 10     now we have o1.i = 25;   so with this the value of I inside the object changed to 25. Next we are creating another object for the same Obj6.class and its address is assigned to o1 gain.  When this is done ,  the address  which o1 held before is over written  and now o1 points to newly created object  the next statement is S.o.p(o1.i); and this obviously  prints   ‘1’  since value of I   inside the new object is  ‘1’   after this we have  Oj6 o2 = o1;  this means pointer variable  o2 assigned the address which o1 is holding now  we have references o1 and o2 to the same object .
This is supported by java.
Note: - A single object can have multiple references.  But a reference can always point only one object.



No comments:

Post a Comment