Sunday, July 14, 2013

Anonymous class in java

Mainly in Java, every class should have a  name. When we are declaring  a class as

class MyTest {
}

Then MyTest is the name of the class. Now, we could create some object of that class as follows.

MyTest obj = new MyTest();

Though we could create an object of an unknow class. Before describing how, I want to share you one more facts. Everyone knows in Java we can not create any object of an interface directly.  We could implements that interface to a concrete class and then we could instantiate an object. So the following line is not possible.

Runnable r = new Runnable();

But we could create an object of Runnable interface without extending directly to a concrete class. What we could do? We will implement the unimplemented method such as run instantly while we creating the object.

Runnable r = new Runnable() {
    public void run() {
        //Do the things you want to do here
    }
};

Look at the above 4 lines, while we are creating

No comments:

Post a Comment