sumit kothalikar wrote:See the following code it is taken from K&B:
I am confused with what really [u ]m3.m1 [/u] at line 1
and m2.m1 at line 2 means.
What is the meaning of m2 object's m1 at line 2.
For these type of questions, please draw a rough diagram, then the picture will be clear!
The key point here is
class Mixer HAS-A m1 of type Mixer(again)
Hello sumit
well what are we doing here?
we are declaring the reference variable m1 of type Mixer
and we are creating object with Mixer m2 = new Mixer();
Now m1 is the instance variable isn't it?
now we can access instance variables of the class using class objects isn't it ?
suppose there is an instance variable int i ;
how do we refer to it if we have object m2?
we refer to it as m2.i
right?
or suppose
we have a instance variable of type Integer
that is
Integer i;
and we can refer to it as m2.i;
in the program
let us go step by step
we are creating the object
also
what happened here? m3 object is created and as we are pasisng m2 to the constructor it is assigned to the reference variable m1 through constructor initialization
and hence m1 is pointing to object of m2() isn't it?
now
m3.m1 will point to the object pointed by m2
and m5.m1 will point to null as m1 is not initialized
Hope this is clear now sumit Happy coding
SCJP 6 [86%] June 30th, 2010
If you find any post useful, click the "plus one" sign on the right
Thanks
Rajiv, Prasad and Moguluri.
I got our point.
Harikrishna Gorrepati
Ranch Hand
Joined: Sep 23, 2010
Posts: 422
posted
0
Hi,
If I change the line 16 to static void go(){ System.out.println("hi"); } , I am not getting Null Pointer Exception..What is the reason ? I just added "static" keyword.
If I change the line 16 to static void go(){ System.out.println("hi"); } , I am not getting Null Pointer Exception..What is the reason ? I just added "static" keyword.
If you declare the method with static, then no need of instance to invoke that method. If you invoked a static method with an instance, the compiler will automatically, handle it as calling it with the class. Not on the object, so if the object reference is null, no problem.
|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|