Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can anyone explain me what is happening at line 8?

 
Tushar Gosalia
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1.class Mixer {
2.Mixer() { }
3.Mixer(Mixer m) { m1 = m; }
4.Mixer m1;
5.public static void main(String[] args) {
6.Mixer m2 = new Mixer();
7.Mixer m3 = new Mixer(m2); m3.go();
8.Mixer m4 = m3.m1; m4.go();
9.Mixer m5 = m2.m1; m5.go();
}
void go() { System.out.print("hi "); }
}
 
harshvardhan ojha
Ranch Hand
Posts: 157
1
Android Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
At line 8, you are calling no arg constructor that you have defined at line 2.
 
harshvardhan ojha
Ranch Hand
Posts: 157
1
Android Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
also for this reason line number 9, will give you NullPointerException as m2 has no object which you are asking it to return.
 
Tushar Gosalia
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No i'm asking about
Mixer m4 = m3.m1; m4.go();
What does this statement mean??And What will be stored in m4??
 
harshvardhan ojha
Ranch Hand
Posts: 157
1
Android Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
m4 will refer to m2 object, as you kept it in m3 and asking it to return that object.
 
Himai Minh
Ranch Hand
Posts: 1250
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Object reference diagram:
m2 -> o where o is an object
m2.m1 -> null
m3 -> o1 where o1 is another object
m3.m1 -> m2 ->o
m4 -> m3.m1-> m2 -> o
m5->m2.m1-> null
So, m5.go() returns a null pointer exception
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic