Why can't I call a method outside of an anonymous class of the same name
The code at the end produces a compile error:
NotApplicable.java:7: run() in cannot be applied to (int)
run(42);
^
1 error
The question is why? Why does javac think I am calling run(), and does not find run(int bar)? It correctly called foo(int bar). Why do I have to use NotApplicable.this.run(42);? Is it a bug?
public class NotApplicable {
public NotApplicable() {
new Runnable() {
public void run() {
foo(42);
run(42);
// uncomment below to fix
//NotApplicable.this.run(42);
}
};
}
private void run(int bar) {
}
public void foo(int bar) {
}
}
Asked by: Paul341 | Posted: 21-01-2022
Answer 1
The explanation for the behavior of your code sample is that this
is defined to be the class that you are currently "most" inside of. In this case, you are "most" inside the anonymous inner class that subclasses runnable and there is no method which matches run(int)
. To broaden your search you specify which this
you want to use by stating NotApplicable.this.run(42)
.
The jvm will evaluate as follows:
this
-> currently executing instance of Runnable
with method run()
NotApplicable.this
-> currently executing instance of NotApplicable
with method run(int)
The compiler will look up the nesting tree for the first method that matches the NAME of the method. –Thanks to DJClayworth for this clarification
The anonymous inner class is not a subclass of the outer class. Because of this relationship, both the inner class and the outer class should be able to have a method with exactly the same signature and the innermost code block should be able to identify which method it wants to run.
public class Outer{
public Outer() {
new Runnable() {
public void printit() {
System.out.println( "Anonymous Inner" );
}
public void run() {
printit(); // prints "Anonymous Inner"
this.printit(); //prints "Anonymous Inner"
// would not be possible to execute next line without this behavior
Outer.this.printit(); //prints "Outer"
}
};
}
public void printit() {
System.out.println( "Outer" );
}
}
Answered by: Owen836 | Posted: 22-02-2022
Answer 2
As far as I recall the rules for selecting a method to run between nested classes are approximately the same as the rules for selecting a method in an inheritance tree. That means that what we are getting here is not overloading, it's hiding. The difference between these is crucial to understanding methods in inheritance.
If your Runnable was declared as a subclass, then the run() method would hide the run(int) method in the parent. Any call to run(...) would try to execute the one on Runnable, but would fail if it couldn't match signatures. Since foo is not declared in the child then the one on the parent is called.
The same principle is happening here. Look up references to "method hiding" and it should be clear.
Answered by: Lenny768 | Posted: 22-02-2022Answer 3
This is because run
is being re-declared when you enter the new Runnable() {}
scope. All previous bindings to run become inaccessible. It's as if you were doing this:
import java.util.*;
public class tmp
{
private int x = 20;
public static class Inner
{
private List x = new ArrayList();
public void func()
{
System.out.println(x + 10);
}
}
public static void main(String[] args)
{
(new Inner()).func();
}
}
The compiler won't look for something that matches the type of x
all the way up the scope stack, it'll just halt when it finds the first references and sees that the types are incompatible.
NOTE: It's not as if it couldn't do this... it's just that, to preserve your own sanity, it's been decided that it shouldn't.
Answered by: John180 | Posted: 22-02-2022Similar questions
java - can we make class that contain main method anonymous
Below is example of anonymous inner class in this we make anonymous class with A
class A
{
void one()
{
System.out.println("hello");
}
}
class One
{
public static void main(String args[])
{
new A()
{
void five()
{
one();
}
}.five();
}
}
My question is can we make class One
How to call the anonymous class method in Java
package innerclasstest;
interface Demo {
}
class Bar {
public void call() {
Foo f = new Foo();
f.doStuff(new Demo() {
public void fall() {
System.out.println("In method args...");
}
});
}
}
class Foo {
public void doStuff(Demo demo) {
System.out.println("In stuff");
}
}
public class ClassArg {
public static void main(String[] args) {
Bar b = new Bar();
...
java - Can't call anonymous class method
This question already has answers here:
java - Cannot call an Anonymous Class Method
I'm trying to call a method, setPostal(String post) I made from an anonymous class, but for some reason the compiler doesnt even recognize it in main. Any reason why this is? Part of my code (address is an inner class of Student):
Student
public class Student implements Gradeable, Cloneable {
String name;
int id;
Address address;
public Student() {
name = "unk...
java - How to call a method from an anonymous class
I have this class that detects when the phone is facing up and when is facing down and prints on the screen Face Up or Face Down!!
package com.example.kyriakos.androiddetectflipping;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android....
java - Use of anonymous class in sort method
why if I put an anonymous class with Comparator in the sort method of List the compiler show me an error?
My code:
public class Example2 {
public static void main(String[] args) {
List<String> l = Arrays.asList("a","b","c","d");
l.sort(Comparator<String> c= new Comparator<>() { //compiler error
public int compare(String a, String b) {
return b.compareTo...
java - Issue in method anonymous class in GWT
I am making a GWT framework similar to Swing framework.
In GWT, I have one method in which I am making a anonymous class in method, but the problem is when this method executes, the execution control does not go to anonymous class instead it skips over it.
After this method executes completely, the control is transfered to the anonymous class. And this thing is working perfectly fine in Swing.
java - Javadoc for method of anonymous object
What is the best way to properly and usefully document a function of an anonymous object? I am doing some programming with Soar (API here), and have code that looks something like this:
/**
*
* @return handler that does blah
*/
public static RhsFunctionInterface functionBlah() {
return new Kernel.RhsFunctionInterface() {
...
java - can we make class that contain main method anonymous
Below is example of anonymous inner class in this we make anonymous class with A
class A
{
void one()
{
System.out.println("hello");
}
}
class One
{
public static void main(String args[])
{
new A()
{
void five()
{
one();
}
}.five();
}
}
My question is can we make class One
java - Method inside anonymous inner class
public void run() {
jmsTemplate.send(new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
byte[] buf = createBytesMessage(5120);
BytesMessage message = session.createBytesMessage();
message.writeBytes(buf);
message.setLongProperty("_publish_time", System.currentTimeMillis());
return message;
} ...
How to call the anonymous class method in Java
package innerclasstest;
interface Demo {
}
class Bar {
public void call() {
Foo f = new Foo();
f.doStuff(new Demo() {
public void fall() {
System.out.println("In method args...");
}
});
}
}
class Foo {
public void doStuff(Demo demo) {
System.out.println("In stuff");
}
}
public class ClassArg {
public static void main(String[] args) {
Bar b = new Bar();
...
java - Can't call anonymous class method
This question already has answers here:
java - Cannot call an Anonymous Class Method
I'm trying to call a method, setPostal(String post) I made from an anonymous class, but for some reason the compiler doesnt even recognize it in main. Any reason why this is? Part of my code (address is an inner class of Student):
Student
public class Student implements Gradeable, Cloneable {
String name;
int id;
Address address;
public Student() {
name = "unk...
java - What calls a method inside an anonymous inner class?
In the example program on
https://gist.github.com/bernii/5697073
In the code
this.wait.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver webDriver) {
System.out.println("Searching ...");
return webDriver.findElement(By.id("resultStats")) != null;
}
}...
java - How to call a method from an anonymous class
I have this class that detects when the phone is facing up and when is facing down and prints on the screen Face Up or Face Down!!
package com.example.kyriakos.androiddetectflipping;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android....
java - Junit test for method with anonymous code block
I need write junit test for method which contains anonymous code block, where override some logic. In my test I need verify if that logic works as should.
for instance:
public void foo(Bar bar) {
Foo myFoo = giveMeFoo(bar, new FooCallBack() {
@Override
public boolean doSomeLogic(SomeObject obj) {
if (obj.xxx == null)
return false;
// do some algorithm
...
java - Should javac find methods outside of an anonymous class of the same name?
This question is a follow up to:
Why can’t I call a method outside of an anonymous class of the same name
This previous question answer why, but now I want to know if javac should find run(int bar)? (See previous question to see why run(42) fails)
If it shouldn't,...
java - Anonymous vs named inner classes? - best practices?
I have a class, let's call it LineGraph, that renders a line graph. I need to subclass it, but the derived class is only used in one place and is coupled to the class that uses it. So I am using an inner class.
I see two ways to do this:
Anonymous inner class
public class Gui {
LineGraph graph = new LineGraph() {
// extra functionality here.
};
}
syntax - Is it possible to make anonymous inner classes in Java static?
In Java, nested classes can be either static or not. If they are static, they do not contain a reference to the pointer of the containing instance (they are also not called inner classes anymore, they are called nested classes).
Forgetting to make an nested class static when it does not need that reference can lead to problems with garbage collection or escape analysis.
Can I compile anonymous or inner classes into a single java .class file?
I am writing a Java class that parses log files. The compiled .class file needs to be loaded into a 3rd party monitoring platform (eG) for deployment and invocation. Unfortunately, the 3rd party platform only allows me to upload a single .class file.
My current implementation has a function to find the 'latest' file in a folder that conforms to a file mask (*CJL*.log) and uses 2 anonymous classes, one to filter...
java - Anonymous inner class in groovy
I am looking into the groovy-wicket integration and lack of anonymous inner classes seems to be a problem when writing the event handlers.
Is there a groovier way of writing this code
import org.apache.wicket.PageParameters
import org.apache.wicket.markup.html.basic.Label
import org.apache.wicket.markup.html.link.Link
import org.apache.wicket.markup.html.WebPage
/**
* Homepage
*/
class HomePage extends ...
How can I pass an anonymous JavaScript object from Java to JavaScript in GWT?
I'm creating a GWT wrapper round a JavaScript library. One of the JavaScript functions takes an anonymous object as its argument e.g.:
obj.buildTabs({ hide: true, placeholder: 'placeholder' });
On the Java side how do I create this type of JavaScript object and pass it to my native implementation?
At the moment, on the Java side I have:
public void buildTabs(TabCon...
java - Anonymous class binary names
I have the following problem:
1) There is some abstract class A with several anonymous subclasses stored in the static fields of A. There is circular dependency between two of the anonymous subclasses. The code of that abstract class is similar to following:
class A implements Serializable
{
public static final A _1 = new A() {
public A foo()
{
return _2;
}
...
Java - Anonymous Inner Class Life Cycle
When using an anonymous inner class as a PropertyChangeListener at what point in the object life cycle is the class garbage collected? After the containing class (SettingsNode) is reclaimed? Should I explicitly remove the PropertyChangeListener in the finalizer of the containing class (SettingsNode)?
public class SettingsNode extends AbstractNode
{
public SettingsNode(Project project, ProjectSettings pr...
java - (nested?) anonymous inner classes for buttons
I've used an anon inner class to get a button obj:
Button modButton = new Button("Modify");
modButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
//TODO: link to a pop-up, and do a refresh on exit
}
});
I want to use this in an arbitrarily sized GWT FlexTable (which is basically an auto re-sizing table).
if i do somethi...
java - Access outer variable from inner anonymous Runnable
The following example code (SSCCE) complains that local variable a must be final.
public class Foo {
final List<A> list = new ArrayList() {{ add(new A()); }};
void foo() {
A a;
Thread t = new Thread(new Runnable() {
public void run() {
a = list.get(0); // not good !
}
});
t.start();
t.join(0);
...
Still can't find your answer? Check out these amazing Java communities for help...
Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)