wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes initialization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "initialization " Watch "initialization " New topic
Author

initialization

shilpa Reddy
Ranch Hand

Joined: Jul 26, 2006
Posts: 42
Given:
class Mixer {
Mixer() { }
Mixer(Mixer m) { m1 = m; }
Mixer m1;
public static void main(String[] args) {
Mixer m2 = new Mixer();
Mixer m3 = new Mixer(m2); m3.go();
Mixer m4 = m3.m1; m4.go();
Mixer m5 = m2.m1; m5.go();
}
void go() { System.out.print("hi "); }
}
What is the result?
A. hi
B. hi hi
C. hi hi hi
D. Compilation fails
E. hi, followed by an exception
F. hi hi, followed by an exception

In the above question is Mixer m1 a static variable. if not then how can Mixer m4 = m3.m1; m4.go(); this piece of code go thru.kindly help
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
hi hi, followed by an exception

m1 is an instance variable. m1 is NULL in m2 referenced object.
[ August 01, 2006: Message edited by: wise owen ]
Naseem Khan
Ranch Hand

Joined: Apr 25, 2005
Posts: 809
In the above question is Mixer m1 a static variable. if not then how can Mixer m4 = m3.m1; m4.go(); this piece of code go thru.kindly help


m1 is not an static variable. m3.m1 means m3 HAS-A variable m1. This m1 is pointing to m2 instance.



Naseem


Asking Smart Questions FAQ - How To Put Your Code In Code Tags
shilpa Reddy
Ranch Hand

Joined: Jul 26, 2006
Posts: 42
how can a static methoed access a non static variable
Naseem Khan
Ranch Hand

Joined: Apr 25, 2005
Posts: 809
That why we are accessing m1 by an object.

m3.m1

Naseem
[ August 01, 2006: Message edited by: Naseem Khan ]
shilpa Reddy
Ranch Hand

Joined: Jul 26, 2006
Posts: 42
thats the question in k&b. i don get you clear
Naseem Khan
Ranch Hand

Joined: Apr 25, 2005
Posts: 809
What I am saying is if you access m1 without any associated object like below, then its not possible and you will get compilation error saying non-static things can't be accessed by its simple name in a static context.

But your are not accessing m1 by its simple name rather you are accessing it by an object.

Following code will not compile



Naseem
[ August 01, 2006: Message edited by: Naseem Khan ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: initialization
 
Similar Threads
explain output
Q4,Self Test, Chapter 3 (K & B)
Please Explain
Exception
assignment