Java does not have type inference provided to C# by the var keyword, so whilst you can create anonymous types they're not much good since you can't get at their attributes.
So you can create an instance of an anonymous class like so:
Object myobj = new Object() {
public final boolean success = true;
}
But since myobj is an instance of Object you can't access success in your code, and as you have created an instance of an anonymous class there is by definition no way to explicitly refer to this class.
In C# var solves this by inferring the type but there is no way to do this in Java.
Normally anonymous classes are used to create implementations of interfaces and abstract classes and so are referenced using the interface or parent class as the type.
Answer from David Webb on Stack OverflowJava does not have type inference provided to C# by the var keyword, so whilst you can create anonymous types they're not much good since you can't get at their attributes.
So you can create an instance of an anonymous class like so:
Object myobj = new Object() {
public final boolean success = true;
}
But since myobj is an instance of Object you can't access success in your code, and as you have created an instance of an anonymous class there is by definition no way to explicitly refer to this class.
In C# var solves this by inferring the type but there is no way to do this in Java.
Normally anonymous classes are used to create implementations of interfaces and abstract classes and so are referenced using the interface or parent class as the type.
With Java 10 you can use anonymous classes:
boolean result = true;
var objResult = new Object() {
boolean success = result;
};
System.out.println(objResult.success);
You can use them with streams:
var names = List.of("John", "Peter", "Olaf");
var namesAndLength = names.stream().map(n -> new Object() {
String name = n;
int length = n.length();
}).collect(toList());
https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html
https://developer.oracle.com/java/jdk-10-local-variable-type-inference