3

I have seen this doing many time but I am bit confused whether or not this would be called as anonymous class?

public class Test {
    public static void main(String[] args) {
        new Thread(){
            @Override
            public void run() {
                System.out.println("##");
            }
        }.start();
    }
}

Reason I am confused is because anonymous classes doesn't have name, but this clearly we already have a "Thread" class in Java API, so this means this has a name, and if it has a name then how it can be a anonymous class, and if it is not a anonymous class then what it is.

I know it is kind of silly but I am not able to reason myself deterministic-ally because I see valid arguments on both side.

Also, in above I can clearly override the run method of Thread class, now if I create my own class let's say MyClass, define some methods in it and then try to do same thing as above then why I cannot override methods of MyClass, they way I was able to override run method of Thread class.

public class MyClass {
    private void myMethod1() {

    }

    private void myMethod2() {

    }
}

public class Test {
    public static void main(String[] args) {
        new MyClass(){
            // why I cannot override "myMethod1" and "myMethod1" of `MyClass`, they way I was able to override `run` method of `Thread` class
        };
    }
}
pjj
  • 2,015
  • 1
  • 17
  • 42
  • 3
    Yes it's anonymous. It is a class that **extends** Thread, and so it does not have a name. – Hovercraft Full Of Eels Apr 28 '17 at 21:37
  • Your 2nd question (and your question shouldn't contain more than one true question) is unclear. You talk about MyClass -- but you don't show it! What methods are you trying to override? Does it even have a `public void start()` method? Please clarify. – Hovercraft Full Of Eels Apr 28 '17 at 21:39
  • @HovercraftFullOfEels That's where I am really messed up and not able to reason, if there is already a class and this is just a extension of class then how it is "anonymous class"? Also, what about my second question related to overriding methods? – pjj Apr 28 '17 at 21:39
  • It is **NOT** the Thread class. It is a class that extends from Thread. You cannot create a variable of this class, other than the inline one. – Hovercraft Full Of Eels Apr 28 '17 at 21:40
  • MyClass doesn't have a start method so your code makes no sense. – Hovercraft Full Of Eels Apr 28 '17 at 21:41
  • @HovercraftFullOfEels Added clarity you had requested. – pjj Apr 28 '17 at 21:41
  • You **can** override the public methods of MyClass, but your farking up your code with some weird `start()` call that again **makes no sense**. – Hovercraft Full Of Eels Apr 28 '17 at 21:41
  • @HovercraftFullOfEels Having `start()` was a typo, corrected now. – pjj Apr 28 '17 at 21:42
  • Come on now, those methods are private. – Hovercraft Full Of Eels Apr 28 '17 at 21:42
  • @HovercraftFullOfEels Like I said I am just messed up, this was just a simple class I created on the fly to show some code so those methods remain private but I swear I had a class which has public methods and I did same thing and I was not able to override them, let me check again may be I was doing that in a inner class. – pjj Apr 28 '17 at 21:45
  • @HovercraftFullOfEels I got it, it was a static method, that's why I was not able to override. – pjj Apr 28 '17 at 21:48

2 Answers2

5
  1. Yes your first class is anonymous since it is inline and extends from Thread. It is not the same as your Thread class.
  2. Regarding MyClass: Of course you can't extend private methods. This has nothing to do with anonymous classes and is basic Java inheritance rules. Make them public and you can extend them inline.

To clarify, if you have a nested class that has a name, you can declare a variable of its type:

public class Test {

    private static class MyThread extends Thread {
        @Override
        public void run() {
            System.out.println("Foo");
        }
    }

    public static void main(String[] args) {
        MyThread myThread = new MyThread();
    }
}

But if you have an anonymous class, you can't do this:

public static void main(String[] args) {
    new Thread(){
        @Override
        public void run() {
            System.out.println("##");
        }
    }.start();


    // how can you declare a variable of the above type *with* its behavior?
}

Side bit: you should almost never extend Thread and instead either implement Runnable, or even better, use executors to help you do your threading.


re:

Ok, thanks for your reply, correct me on my understanding - using anonymous class I can create a brand new class (basically implementation of an interface) at runtime, also I can extend an existing class and that would still be called as "anonymous class"?

Yes, you do create a brand new class, but no you do not necessarily implement an interface. In fact your example above has nothing directly to do with interfaces and all to do with extending an extant concrete class. You can and often do create anonymous classes that implement interfaces, with Runnable being a common example, but your example above is not "basically implementation of an interface".

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Ok, thanks for your reply, correct me on my understanding - using anonymous class I can create a brand new class (basically implementation of an interface) at runtime, also I can extend an existing class and that would still be called as "anonymous class"? – pjj Apr 28 '17 at 21:57
  • @pjj: see edits above. Your question suggests that you may want to study this topic and some other topics including what interfaces are in any decent Java text book. Note that when I was first learning Java, I bought a bunch of books, many of them 2nd hand, and I do not regret doing this. – Hovercraft Full Of Eels Apr 28 '17 at 22:00
  • I think I got my confusion cleared, it's just that I am bad with explanations, but here is another try - "Using anonymous class I can not only implement an interface at runtime but also extend a class at runtime". – pjj Apr 28 '17 at 22:02
  • I just read your edit, yes what I am showing here is not dealing with "implement interface" but my point was more in general. – pjj Apr 28 '17 at 22:03
  • @pjj: please have a look [anonymous classes](http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html) – Hovercraft Full Of Eels Apr 28 '17 at 22:04
  • Yes I know I am bad in explanations but my concept was correct, and all my confusion related to these anonymous classes were cleared by you, thanks again for your time to reply. – pjj Apr 28 '17 at 22:06
  • I am just running too fast, learning and doing many things, hope tide will settle soon. – pjj Apr 28 '17 at 22:07
2

public class Thread extends Object implements Runnable

So you're basically creating anonymous class of Class Thread but because Thread Class implements Runnable (which is functional interface that has one abstract method) -> you have then to @override run() method which comes from Runnable Interface

Yahya
  • 13,349
  • 6
  • 30
  • 42