0

So I was looking at a tutorial and saw this line of code:

Thread timer = new Thread() {
  @Override 
  public void run(){
    // etc....
  }
}

What is happening here? They are creating a new object of the Thread class and declaring the method run when creating that object? How is this possible? My understanding was that an object got its methods from its class?

amaidment
  • 6,942
  • 5
  • 52
  • 88
liveleker
  • 11
  • 2

2 Answers2

0

This is an Anonymous Class. It is defining/creating the class, but overriding or implementing a method in that class in this one place. The anonymous class cannot be called/created elsewhere.

When your program runs the code where this anonymous class is defined, it will create an object of this class, with the methods that you have defined in it. Any subsequent calls to those methods of that created object will use the overridden methods that you have defined.

This can be used for classes (if they are not final), abstract classes and interfaces.

amaidment
  • 6,942
  • 5
  • 52
  • 88
0

This mecanism is called Anonymous Classes. So, you can declare new instance of class by implementing all abstact members. In this code your implement an anonymous instance of Thread, by implemnting public void run() method, so you can declare your functionality inside the body.

More info here: https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html

DoSofRedRiver
  • 420
  • 5
  • 9