Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Anonymous Inner Class Problem

 
Philani Dlamini
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Everone.
In my practice code snippet im passing a local anonymous inner class to a method that expects an interface type. Im also using a plain old anonymous inner class to sub-class and add some functionality to my ferrari class.

Can someone please explain to me why my output returns only:

"Ferrari travels at 390 KPH"

and does not output:

"The ferrari has stopped"

-----------------------------------------------


public class Parent{

public static void main(String argsp[]){

Ferrari f = new Ferrari();
f.Foward(new Car(){
public void go(){
System.out.println("Ferrari travels at 390 KPH");
}
}
);
f.Stop();

}
}

class Ferrari{

public void Foward(Car object){

object.go();
}

public void Stop(){
Ferrari fi = new Ferrari(){
public void Stop(){
System.out.println("The ferrari has stopped");

}

} ;

}

}


interface Car{

public void go();


}
 
Shivani Chandna
Ranch Hand
Posts: 380
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Ok so in your Stop() method you have another anon class defined - having the new definition of Stop() method within Stop method itself.

So well I think that the control is going into Ferrari's existing Stop method (1) but after defintion - nothing happens. You need to call the newly defined Stop() method within existing Stop method . So --




I think the (2) should do. It should not become a recursive call - which it could have - had the class not been redefined anonymously within this method.


-Cheers,
Shivani.
 
Philani Dlamini
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Shivani

Tnx for reading through that long un-indented code snippet.
Deep down, i guess i was hoping the call would be recursive.

call at (2) is neccessary then...tnx
 
Henry Wong
author
Marshal
Pie
Posts: 21212
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Philani Dlamini:
Hi Shivani

Tnx for reading through that long un-indented code snippet.
Deep down, i guess i was hoping the call would be recursive.

call at (2) is neccessary then...tnx


I am not a fan of recursion for no reason -- but I guess it the best way to learn it.

Your inner's inner class is running... but remember it is not calling the stop method from the constructor, it is calling the go() method. So... in your stop methods inner class, if you override the go() method instead, it should work. It is kinda awkward, but it should work.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic