Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

initialization

 
shilpa Reddy
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 809
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
shilpa Reddy
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how can a static methoed access a non static variable
 
Naseem Khan
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That why we are accessing m1 by an object.

m3.m1

Naseem
[ August 01, 2006: Message edited by: Naseem Khan ]
 
shilpa Reddy
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thats the question in k&b. i don get you clear
 
Naseem Khan
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic