Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

260
Visualizações
Would this implementation be called as anonymous class?

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
        };
    }
}
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

  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".

over 4 years ago · Santiago Trujillo Relatório

0

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

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda