Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a class and create an instance of it as one construct

Tags:

java

I would like to reduce the following lines of code. It shouldn't be necessary to declare the class and then create an instance of it to get the run method to run. It should be possible to write the code such that you can define the class and create an instance of it as one construct. I still need the runOnUiThread to actually run it but I am looking for a condensed way to combine the class definition and instantiation. I've seen it done somewhere but can't recall how it's done:

class OnRunnableCompleted implements Runnable
{
  @Override
  public void run()
  {
  }
}

OnRunnableCompleted onRunnableCompleted = new OnRunnableCompleted();
runOnUiThread(onRunnableCompleted);
like image 945
Johann Avatar asked Dec 09 '22 14:12

Johann


2 Answers

runOnUiThread(new Runnable() { public void run() {} });

This creates an anonymous class that implements the Runnable interface and overrides the abstract run() method to be a no-op.

The general form of an anonymous class is

new Name(superCtorParam0, superCtorParam1) {
  member0;
  member1;
}

where

  1. Name is the name of an interface or class to extend/implement,
  2. superCtorParam0...n are parameters to Name's constructor
  3. member0...n are the fields, methods, initializers, inner classes of the anonymous class just like in any other class declaration
like image 146
Mike Samuel Avatar answered Dec 11 '22 02:12

Mike Samuel


How about...

Runnable calculatePI = new Runnable(){
    public void run(){/*calculate pi*/}
}
//Any time you need to calculate pi
runOnUiThread(calculatePI);

This reduces the code and prevents the repeated creation of anonymous classes. In my android development I use this solution quite often. Works well.

like image 36
William Morrison Avatar answered Dec 11 '22 02:12

William Morrison