Create and use an anonymous object in Java
An anonymous object is an object created without any name assigned to that object.
When you create an object in Java, you usually would assign a name to the object.
In the code below, a newly instantiated Person object is assigned to the reference variable nathan :
The reference variable nathan points to the Person object instance, so anytime you want to use or manipulate that object in your code, you call it with the variable name.
On the other hand, an anonymous object is not assigned to a reference variable on instantiation, so you can’t refer to the object after it has been instantiated.
In the following code, the call() method of a new Person object is called directly:
Although it isn’t common, an anonymous object is useful when you need an object no more than once in your program. You can still call on its methods as if they are static methods.
The following shows how you can use anonymous objects to call on their methods:
Since Java 10, you can also create and store an anonymous object during instantiation by saving the instance with the var keyword.
In the code below, a new Object is created and referenced from myObj reference variable:
The var keyword in Java 10 will infer the type of the variable based on the surrounding context.
Inside the new Object() body, you can define variables and methods that the object instance will have.
After that, you can call and use the instance variables and methods just like a normal object.
Now you’ve learned how to create and use anonymous objects in Java. Good work! 👍
Take your skills to the next level ⚡️
I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!
About
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.
Search
Type the keyword below and hit enter
Tags
Click to see all tutorials tagged with:
Anonymous object in Java
Anonymous object in Java means creating an object without any reference variable. Generally, when creating an object in Java, you need to assign a name to the object. But the anonymous object in Java allows you to create an object without any name assigned to that object.
So, if you want to create only one object in a class, then the anonymous object would be a good approach. Reading this article, you will learn what an anonymous object is and how to create and use anonymous objects in Java.
Anonymous Object in Java
Anonymous means Nameless. An anonymous object is basically a value that has been created but has no name.
Since they have no name, there’s no other way to refer to them beyond the point where they are created. Consequently, they have “expression scope,” meaning they are created, evaluated, and destroyed everything within a single expression.
However, an anonymous object is considered useful when you want to create an object not more than once in your program.
Here is the syntax to create an anonymous object in Java.
Syntax
Example
Here’s how we can pass the parameter to the constructor −
If you wish to call a method through the anonymous object, here’s how the code is written −
This is a way how you can pass the parameter to the calling method −
new Student().display(“Jose”, 15);
Here’s a program that illustrates the above concept −
public class Addition // Declaring the instance variables. int a; int b; int c; int d; // Declaring the parameterize constructor and initializing the parameters. Addition(int p, int q) a = p; b = q; int ab = a + b; System.out.println("Addition of a and b:" +ab); > // Declaring an instance method and initializing parameters. void addition(int x, int y ) c = x; d = y; int cd = c + d; System.out.println("addition of c and d:" +cd); > public static void main(String[] args) // Creating an anonymous object and passing the values to the constructor and calling method. new Addition(2,2).addition(1, 5); // We are also allowed to pass the different values with the same anonymous object. // but we should not create another new anonymous object. new Addition(4,10).addition(5, 15); > >
Output
Addition of a and b: 4 Addition of c and d: 6 Addition of a and b: 14 Addition of c and d: 20
Example
Here’s another program where we will create an anonymous object and calculate the area and perimeter of the square by passing different values to the constructor and method.
package anonymousObject; public class Calculation // Declare instance variable. int a; // Declaration of one parameter constructor. Calculation(int p) a = p; > // Declaration of instance methods. void area() int area = a * a; System.out.println("Area of square: " +area); > void perimeter(int b) int peri = 4 * b; System.out.println("Perimeter of square: " +peri); > public static void main(String[] args) // Create an anonymous object. new Calculation(50).area(); new Calculation(10).perimeter(100); new Calculation(20).area(); new Calculation(30).perimeter(200); > >
Output
Area of square: 2500 Perimeter of square: 400 Area of square: 400 Perimeter of square: 800
How to create and use Anonymous Object in Java −
The following program shows how you can use anonymous objects to call on their methods −
class Person void call(String name) System.out.println("Hello, " + name + "!"); > int sum(int x, int y) return x + y; > > new Person().call("Jose"); // Hello, Jose! int calculation = new Person().sum(7, 31); System.out.println(calculation); // 38
Due to Java 10, you can create and save an anonymous object during instantiation by storing the instance with the var keyword.
In the below program, you can see how a new Object is created and referenced from the myObj reference variable −
boolean result = true; var myObj = new Object() void greetings() System.out.println("Hello World!"); > boolean success = result; >; System.out.println(myObj.success); // true myObj.greetings(); // Hello World!
Depending on the surrounding context, the var keyword in Java 10 will infer the type of the variable.
Inside the new Object() body, you can also define variables and methods that the object instance will hold. Following, you can call and use the instance variables and methods simply like a normal object.
Wrapping up
From the above discussion, we hope now you’re well aware of what anonymous object in Java is and how to create and use them. Additionally, you would also be understood that by using an Anonymous object in Java, you can write less code and create only one object in a class. More importantly, you don’t want to write unused code, and you also prevent code from being used outside of the required scope.
If you like reading this article and you find it useful, give us a thumbs up that would inspire us to give you more useful technical stuff.
Anonymous objects in java
У меня в идее все декларирует(компиляторо не ругается) я декларировал и переменные статические и создавал статические методы, другой вопрос что статику из анонимного класса не достать. Почему автор так написал? Может я что то не так понял? Есть ответы: Внутренний анонимный класс может содержать статические переменные и методы c версии Java 16! Статические методы или переменные достать можно, просто нужно обратиться к ним в main методе внутри воложеного класса: System.out.println(staticInt); Иначе как сделать извлечение статик элементов из анонимного класса я не придумал.
Предыдущая статья про нестатические вложенные классы (1/3 часть): https://javarush.com/groups/posts/2181-vlozhennihe-vnutrennie-klassih Продолжение про статические вложенные классы (3/3 часть): https://javarush.com/groups/posts/2183-staticheskie-vlozhennihe-klassih
вот кое что не понятно. Тут написано: «Если каждому из наших анонимных классов-модулей понадобится какое-то отличающееся поведение, свои специфические методы, которых нет у других, мы легко можем дописать их:»
MonitoringSystem generalModule = new MonitoringSystem() < @Override public void startMonitoring() < System.out.println("Мониторинг общих показателей стартовал!"); >public void someSpecificMethod() < System.out.println("Специфический метод только для первого модуля"); >>;
Вопрос. А имеет смысл такие методы вообще писать (даже если пропустит компилятор)? будет ли вообще хоть какая-нибудь возможность достучаться до специфического метода? Ведь данный метод существует лишь в анонимном классе, имя которого нам не известно. Объект анонимного класса хранится в переменной типа интерфейса. Данному интерфейсу ничего не известно о данном методе (который есть только у наследника — в анонимном классе). И компилятор по этой причине не позволит к нему обратиться. Более того, мы не сможем создать ссылочную переменную типа анонимного класса и перекинуть туда объект, чтобы вызвать данный метод — по причине того, что нам банально не известно имя анонимного класса, чтобы создать ссылочную переменную данного типа. Я прав?
Супер лекция. Еще бы компоновали ссылки в конце по смежным темам(здесь например по всем типам вложенных классов). А то искать через поисковик неудобно. Или я чего-то не догоняю.
import java.util.Scanner; interface Eatable < public void eat(); >public class Test < public static final Scanner menu = new Scanner(System.in); public static final String whatWouldULikeToEat = menu.nextLine(); public static void main(String[] args) < Eatable eatable = new Eatable() < @Override public void eat() < System.out.printf("Well, I would like to eat %s, please.", whatWouldULikeToEat); >public String receipt() < return whatWouldULikeToEat; >>; eatable.eat(); System.out.println("\nOkay, sir."); > >
Важный момент в том, что дополнительные методы, помимо тех, что мы переопределяем, нельзя использовать извне этого анонимного класса, а только внутри него. Т.е. в примере:
MonitoringSystem generalModule = new MonitoringSystem() < @Override public void startMonitoring() < System.out.println("Мониторинг общих показателей стартовал!"); >public void someSpecificMethod() < System.out.println("Специфический метод только для первого модуля"); >>;
Anonymous object in Java
An object which has no reference variable is called anonymous object in Java.
Anonymous means nameless. If you want to create only one object in a class then the anonymous object is a good approach.
Declaration of Anonymous object
The syntax to create an anonymous object in Java is given below.
For example:
new Student();
We can pass the parameter to the constructor like this:
new Student(“Shubh”);
If you want to call a method through the anonymous object then you can write code like this:
new Student().display();
We can also pass the parameter to the calling method like this:
new Student().display(“Shubh”, 25);
Program code 1:
package anonymousObject; public class Multiplication < // Declare the instance variables. int a; int b; int c; int d; // Declare the parameterize constructor and initialize the parameters. Multiplication(int p, int q) < a = p; b = q; int ab = a * b; System.out.println("Multiplication of a and b:" +ab); >// Declare an instance method and initialize parameters. void multiply(int x, int y ) < c = x; d = y; int cd = c * d; System.out.println("Multiplication of c and d:" +cd); >public static void main(String[] args) < // Create the anonymous object and pass the values to the constructor and calling method. new Multiplication(25,25).multiply(10, 20); // We can also pass the different values with the same anonymous object. // but we cannot create another new anonymous object. new Multiplication(20,20).multiply(30, 30); >>
Output: Multiplication of a and b: 625 Multiplication of c and d: 200 Multiplication of a and b: 400 Multiplication of c and d: 900
Let’s make another program where we will create an anonymous object and calculate area and perimeter of square by passing different values to constructor and method.
Program code 2:
package anonymousObject; public class Calculation < // Declare instance variable. int a; // Declaration of one parameter constructor. Calculation(int p) < a = p; >// Declaration of instance methods. void area() < int area = a * a; System.out.println("Area of square: " +area); >void perimeter(int b) < int peri = 4 * b; System.out.println("Perimeter of square: " +peri); >public static void main(String[] args) < // Create anonymous object. new Calculation(50).area(); new Calculation(10).perimeter(100); new Calculation(20).area(); new Calculation(30).perimeter(200); >>
Output: Area of square: 2500 Perimeter of square: 400 Area of square: 400 Perimeter of square: 800
Hope that this tutorial has covered all important points related to anonymous object. Remember the following points related to Java anonymous object.
1. A class that does not have name is called anonymous class in Java. It can be defined inside a method without a name.
2. The object of an anonymous class is created in the same place where it is defined. It cannot have explicit constructors.
3. An object that does not have reference variable is called anonymous object. It is not stored in a variable.
4. Java anonymous object creation is useful when it is not used more than once.
Thanks for reading.
Next ⇒ Types of classes in Java ⇐ Prev Next ⇒