Answer the question
In order to leave comments, you need to log in
Why are anonymous classes needed in java and how to access them?
package practice;
public class Practice {
public static void main(String[] args) {
}
}
class Classes {
class Inner {
void meth3() {
//Анонимный класс
Classes x1 = new Classes() {
//действия
};
}
}
}
Answer the question
In order to leave comments, you need to log in
This is not an anonymous class, but an inner class. You can access it from anywhere in the outer class, as well as from yourself.
And the anonymous class, as the name suggests, has no name. And it is created, for example, from an interface, implementing its methods in place.
Inner classes can be private (private/protected) by default and will be visible only from the outer class, or they can be public (public static) and be available to the entire application. Usually used to keep the class file structure low and for internal use as temporary storage and wrappers.
An anonymous class is created at the place of use and is used in a specific place in the application. In the example below, we write to the thread variable an instance of a newa class that inherits from Thread with an overloaded run method
class MyThread
{
public static void main(String[] args)
{
// Создаем расширение стандартного класса Thread с переопределением метода run()
Thread thread = new Thread()
{
public void run()
{
System.out.println("Child Thread");
}
};
thread.start();
System.out.println("Main Thread");
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question