if you mean an anonymous function, and are using a version of Java before Java 8, then in a word, no. (Read about lambda expressions if you use Java 8+)

However, you can implement an interface with a function like so :

Comparator<String> c = new Comparator<String>() {
    int compare(String s, String s2) { ... }
};

and you can use this with inner classes to get an almost-anonymous function :)

Answer from chris on Stack Overflow
🌐
Oracle
docs.oracle.com › javase › tutorial › java › javaOO › anonymousclasses.html
Anonymous Classes (The Java™ Tutorials > Learning the Java Language > Classes and Objects)
In this example, the method invocation btn.setOnAction specifies what happens when you select the Say 'Hello World' button. This method requires an object of type EventHandler<ActionEvent>. The EventHandler<ActionEvent> interface contains only one method, handle. Instead of implementing this method with a new class, the example uses an anonymous class expression.
🌐
W3Schools
w3schools.com › java › java_anonymous.asp
Java Anonymous Class
You often use anonymous classes to override methods of an existing class or interface, without writing a separate class file.
Discussions

anonymous method java
What you are basically doing is creating a new anonymous class that extends A. In that class you are adding a method f2. That method is only known for the anonymous class, not for A. Your variable is of type A, so you cant call the f2 method on it. You can declare the variable a as var instead of A. You will need Java 11 or higher for that. Then the compiler will allow you to call the f2 method, because the variable a will have the type of your anonymous class. However this is not really something you would ever want to do. Creating anonymous classes usually only serves the purpose to override existing methods of the other class. Basically just extend the class without putting it into a new file. So you would only use it to extend a method that already exists in A. Is there anything specific you are trying to accomplish? More on reddit.com
🌐 r/learnjava
6
2
February 19, 2023
java - Using methods on anonymous classes - Stack Overflow
If I understand your question/assignment properly (and I'm not sure that I do, what exactly are the requirements of the assignment? Are you required to use anonymous classes? There's really no such thing as an anonymous method in Java, only anonymous classes.), it sounds like you might want ... More on stackoverflow.com
🌐 stackoverflow.com
java - Invoking a method of an anonymous class - Stack Overflow
Well, if you create an anonymous ... an anonymous implementation of an interface), you can hold onto the reference in a variable that would let you call those methods at will. ... The only way to access hello through static typing is to access it on the immediate expression, yes. ... Also note that Java 8 has a nice ... More on stackoverflow.com
🌐 stackoverflow.com
[Java] can someone explain anonymous classes (and perhaps how it ties into lamda) in layman terms?
An anonymous class is simply one that isn't defined with a (new) class name. This is useful for cases where an implementation of a function is needed but is only used once. This is sometimes the case in event handlers. For example, imagine the following situation where anonymous classes aren't used: // Probably defined elsewhere interface EventListener { public void handle(); } class Handler1 implements EventListener { public void handle() { System.out.println("A"); } } class Handler2 implements EventListener { public void handle() { System.out.println("B"); } } class Handler3 implements EventListener { public void handle() { System.out.println("C"); } } As you can probably see, a lot of classes need to be introduced, and if these are for one specific purpose there won't be any use in keeping these classes around bar for registering them as event listeners once. More on reddit.com
🌐 r/learnprogramming
4
1
May 9, 2021
Top answer
1 of 6
86

if you mean an anonymous function, and are using a version of Java before Java 8, then in a word, no. (Read about lambda expressions if you use Java 8+)

However, you can implement an interface with a function like so :

Comparator<String> c = new Comparator<String>() {
    int compare(String s, String s2) { ... }
};

and you can use this with inner classes to get an almost-anonymous function :)

2 of 6
48

Here's an example of an anonymous inner class.

System.out.println(new Object() {
    @Override public String toString() {
        return "Hello world!";
    }
}); // prints "Hello world!"

This is not very useful as it is, but it shows how to create an instance of an anonymous inner class that extends Object and @Override its toString() method.

See also

  • JLS 15.9.5 Anonymous Class Declarations

Anonymous inner classes are very handy when you need to implement an interface which may not be highly reusable (and therefore not worth refactoring to its own named class). An instructive example is using a custom java.util.Comparator<T> for sorting.

Here's an example of how you can sort a String[] based on String.length().

import java.util.*;
//...

String[] arr = { "xxx", "cd", "ab", "z" };
Arrays.sort(arr, new Comparator<String>() {
    @Override public int compare(String s1, String s2) {
        return s1.length() - s2.length();
    }           
});
System.out.println(Arrays.toString(arr));
// prints "[z, cd, ab, xxx]"

Note the comparison-by-subtraction trick used here. It should be said that this technique is broken in general: it's only applicable when you can guarantee that it will not overflow (such is the case with String lengths).

See also

  • Java Integer: what is faster comparison or subtraction?
    • Comparison-by-subtraction is broken in general
  • Create a Sorted Hash in Java with a Custom Comparator
  • How are Anonymous (inner) classes used in Java?
🌐
Baeldung
baeldung.com › home › java › core java › anonymous classes in java
Anonymous Classes in Java | Baeldung
June 11, 2024 - we create an instance of an anonymous class that implements interface ActionListener. Its actionPerformed method gets triggered when a user clicks the button. Since Java 8, lambda expressions seem to be a more preferred way though.
🌐
Reddit
reddit.com › r/learnjava › anonymous method java
r/learnjava on Reddit: anonymous method java
February 19, 2023 -

I kind of learnt about anonymous and functional methods, but I am confused here:

public abstract class A {
	public void f1(String str) {
		System.out.println(str);
	}
	
	public static void main(String[]args) {
		A a = new A() 
		{
		public void f2(String str) {
			
			}
		};
	a.f2("abc");
	}
}

I have error in line
a.f2("abc")

lets say I want to use f2 method (the anonymous function) how could I use it outside of A? or is it possible only inside A ?

Top answer
1 of 5
5
What you are basically doing is creating a new anonymous class that extends A. In that class you are adding a method f2. That method is only known for the anonymous class, not for A. Your variable is of type A, so you cant call the f2 method on it. You can declare the variable a as var instead of A. You will need Java 11 or higher for that. Then the compiler will allow you to call the f2 method, because the variable a will have the type of your anonymous class. However this is not really something you would ever want to do. Creating anonymous classes usually only serves the purpose to override existing methods of the other class. Basically just extend the class without putting it into a new file. So you would only use it to extend a method that already exists in A. Is there anything specific you are trying to accomplish?
2 of 5
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
NashTech Blog
blog.nashtechglobal.com › home › anonymous functions in java : begineers
Anonymous Functions in JAVA : Begineers - NashTech Blog
November 2, 2021 - If you mean anonymous function(function literal, lambda abstraction) then you are using a Java 8 version. Anonymous function is a function define as not bound to an identifier. Because,These are a form of nested function in allowing access to ...
🌐
Medium
medium.com › @nagarjun_nagesh › lambda-functions-vs-anonymous-inner-classes-in-java-80893c2214d5
Lambda Functions vs. Anonymous Inner Classes in Java | by Nagarjun (Arjun) Nagesh | Medium
February 23, 2024 - In this example, we define a functional interface `Calculator` with the abstract method `calculate(int a, int b)`. We then use lambda functions to implement the `Calculator` interface for addition and subtraction operations. Before Java 8, anonymous inner classes were commonly used to implement functional interfaces.
Find elsewhere
🌐
AlgoMaster
algomaster.io › home › java › anonymous classes
Anonymous Classes | Java | AlgoMaster.io
June 2, 2026 - Runnable is a built-in interface with one method: run. The anonymous class implements it, prints a line, and gets stored in greeting. Calling greeting.run() invokes the body of the anonymous class. An anonymous class isn't magic. The compiler turns it into a real class with a synthetic name. If your file is Outer.java, the first anonymous class declared inside Outer becomes a class file named Outer$1.class, the second becomes Outer$2.class, and so on.
🌐
Judahstutorials
judahstutorials.com › java-anonymous-class-primer
Java Anonymous Class Primer – Original – Judah's Tutorials
For further information, see the Comparator Javadoc Page. List.sort(Comparator<T> cmp) is a method declared by the List<T> interface that sorts a list according to the comparison rule implemented by cmp. The explicit declaration of ReverseSorter in the above example can be replaced with an anonymous class declaration/instantiation.
🌐
Cornell Computer Science
cs.cornell.edu › courses › JavaAndDS › files › anonymousFunction.pdf pdf
The anonymous function, or lambda ÓDavid Gries, 2018
anonymous function —anonymous because the function is not given a name. The list of parameters is there (though · their types need not be given), the function body is there (though in this case braces are not needed), but the function
🌐
CodingNomads
codingnomads.com › java-anonymous-inner-class
Primer: What is an Anonymous Class in Java
As you can see, you have skipped the step of creating the class that implements the interface, and you've gone straight to creating an object of the interface - this is known as an anonymous inner class. The only way to create an object of an interface (without using a dependency injection framework such as Spring) is by implementing the abstract methods in-line immediately upon creating that object, as you have done in the example above.
🌐
Programiz
programiz.com › java-programming › anonymous-class
Java Anonymous Class
Note: Anonymous classes are defined inside an expression.
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › anonymous class in java
A Complete Guide to Anonymous Class in Java with Examples
March 6, 2025 - This tutorial explores the concept of anonymous classes in Java, their syntax, practical examples, and best practices to help you write cleaner and more efficient code. ... Software Development courses — take the next step in your learning journey! ... Java unique is that they can directly access variables and methods of the enclosing class (including final or effectively final variables)
🌐
DEV Community
dev.to › satyam_gupta_0d1ff2152dcc › java-anonymous-class-explained-no-more-confusion-5987
Java Anonymous Class Explained: No More Confusion - DEV Community
October 20, 2025 - The Rule of Thumb: If you are implementing a functional interface (like Runnable, Comparator, ActionListener), use a lambda. It's more concise and efficient. For everything else (multiple-method interfaces, extending classes), you need an anonymous class. ... java // So much cleaner!
🌐
Hyperskill
hyperskill.org › university › java › java-anonymous-class
Java Anonymous Class
November 25, 2024 - The syntax of an anonymous class is an expression. And it's similar to a constructor call except that there is a class definition contained in a block of code. An anonymous class must override all abstract methods of the superclass. That is, all interface methods must be overridden except default ...
🌐
Tutorialspoint
tutorialspoint.com › java › java_anonymous_class.htm
Java - Anonymous Classes
You can use an anonymous inner class to implement an interface in Java.
🌐
Baeldung
baeldung.com › home › java › core java › lambda expression vs. anonymous inner class
Lambda Expression vs. Anonymous Inner Class | Baeldung
January 8, 2024 - An anonymous class provides a class definition and instantiates it at the same time. We use the new keyword and the name of the class or interface we’re implementing. It’s like calling the constructor, but we also provide method implementations ...
Top answer
1 of 4
17

Can somebody point me to the part of the specification that addresses this?

This will mostly be defined in the section concerning Method invocation expressions:

The first step in processing a method invocation at compile time is to figure out the name of the method to be invoked and which class or interface to search for definitions of methods of that name.

For the class or interface to search, there are six cases to consider, depending on the form that precedes the left parenthesis of the MethodInvocation:

  • [...]
  • If the form is Primary . [TypeArguments] Identifier, then let T be the type of the Primary expression. The class or interface to search is T if T is a class or interface type, or the upper bound of T if T is a type variable.

Here, the Primary expression is the class instance creation expression. So the type to search is the anonymous type.

Am I right in thinking that the only way you can invoke hello is immediately like this. What about reflection?

As long as an expression evaluates to the anonymous type T, whether through direct access like you have, or through generics, you have access (regular access rules apply) to the members that T declares. This isn't limited to methods. You can access fields or types, though it's not as useful for types. For example,

Object var = new Object() {
    class Nested {
    }
}.new Nested();

Since there's no way to refer to the nested type without the enclosing type, you can't declare a variable of that nested type. The usefulness declines very quickly. (Presumably, that's also why you can't have a static nested type within this anonymous class.)

Reflection also exposes this method. The generated anonymous class contains this method, so you can retrieve it and invoke it. The process is the same. The fact that the instance is from an anonymous class doesn't matter. The same strategy as presented in How do I invoke a Java method when given the method name as a string? applies.

For example,

Object ref = new Object() {
    public void method() {
        System.out.println("hidden");
    }
};
Class<?> anonymousClass = ref.getClass();
Method method = anonymousClass.getMethod("method");
method.invoke(ref, new Object[0]);

Don't ever write code like this.

2 of 4
12

As posted, there isn't a way to get the anonymous methods from the Object instance. And, it makes Anonymous classes look pointless. But, you could (and I usually would) use it to implement an interface. Something like,

static interface Hello {
    void hello();
}
public static void main(String[] args) {
    Hello o = new Hello() {
        public void hello() {
            System.out.println("Hello World!");
        }
    };
    o.hello();
}

Or, more commonly, for call-backs with JFC/Swing and ActionListener.

🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java
Java 8 Anonymous Function Example - Java Code Geeks
February 25, 2019 - Notice that the instance variable inner is accessible inside the anonymous implementation of addNumbers(...)method; however, outer variable, which is an instance variable of the encapsulating class is not accessible just like that; to access outer inside the anonymous implementation, we would have to use the following construct: Encapsulator.this.outer