How do I pass a object to an implement and pass the local object to object that is outside? I think the SwingUtilities.invokeLater is nessasary for a Swing object , right?
Sensors sens = new Sensors();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
GUI application = new GUI(sens);
application.getJFrame().setVisible(true);
}
});
SMS sms = new SMS(application);
this is me try to solve the problem , but i get a No enclosing instance of type GUI is accessible. Must qualify the allocation with an enclosing instance of type GUI (e.g. x.new A() where x is an instance of GUI). problem.
// in main
Sensors sens = new Sensors();
GUI application = null;
SwingUtilities.invokeLater(new GUIthread(sens , application));
SMS sms = new SMS(application);
//a class inside GUI.java , but not inside GUI class
class GUIthread implements Runnable{
Sensors s;
GUI g;
public GUIthread(Sensors s , GUI g){
this.s = s;
this.g = g;
}
#Override
public void run() {
// TODO Auto-generated method stub
g = new GUI(s);
g.getJFrame().setVisible(true);
}
}
the sourcecode
This problem arises when you try to create an instance of a non-static inner class in a context that does not specify (or imply) an instance of the enclosing class.
From this, I deduce that you have declared one of your classes as a non-static inner class; e.g. something like this:
public class Outer {
...
public class Inner {
public Inner() {
...
}
...
}
...
}
If you now try to create an instance of Inner in some other code using new Inner(), you will get a compilation error like the one you are seeing.
You can do one of two things to "fix" the problem:
If you change public class Inner { to public static class Inner {, you can use new Inner() as you are currently doing. But this will mean that the code of Inner cannot access the (final) instance variables of the enclosing class; i.e. Outer.
If you don't want to change Inner to a static class, you will need to instantiate it as follows:
Outer outer = ...
...
Inner inner = outer.new Inner(); // qualified creation
FOLLOWUP
any down side using static class to call swing?
Only the one that I identified above.
SO , all the instantiate happen inside Outer constructor? right?
No. The code in the "qualified creation" example above can appear anywhere that the Inner class is accessible. And since we declared it as public ...
If you instantiate Inner inside a constructor (or instance method) for Outer, you can just use new Inner(). The enclosing Outer instance is the same as this.
Try
final Sensors sens = new Sensors();
instead.
Easy, declare the reference final and it will be seen by the anon class code.
I agree with Zach and suspect that GUIthread is an inner class. If so, you may do well to make it a stand-alone class or a static inner class, but it's difficult to know if this is the true solution without more information and without the actual error message.
Related
Is there any way to access the methods of local inner classes in Java. Following code is the sample code that I tried before. According to that what is the mechanism to access the mInner() method?
class Outer{
int a=100;
Object mOuter(){
class Inner{
void mInner(){
int y=200;
System.out.println("mInner..");
System.out.println("y : "+y);
}
}
Inner iob=new Inner();
return iob;
}
}
class Demo{
public static void main(String args[]){
Outer t=new Outer();
Object ob=t.mOuter();
ob.mInner(); // ?need a solution..
}
}
As ILikeTau's comment says, you can't access a class that you define in a method. You could define it outside the method, but another possibility is to define an interface (or abstract class). Then the code would still be inside your method, and could access final variables and parameters defined in the method (which you couldn't do if you moved the whole class outside). Something like:
class Outer {
int a = 100;
public interface AnInterface {
void mInner(); // automatically "public"
}
AnInterface mOuter() { // note that the return type is no longer Object
class Inner implements AnInterface {
#Override
public void mInner() { // must be public
int y = 200;
System.out.println("mInner..");
System.out.println("y : " + y);
}
}
Inner iob = new Inner();
return iob;
}
}
class Demo {
public static void main(String[] args) { // the preferred syntax
Outer t = new Outer();
Outer.AnInterface ob = t.mOuter();
ob.mInner();
}
}
Note: not tested
Note that the return type, and the type of ob, have been changed from Object. That's because in Java, if you declare something to be an Object, you can only access the methods defined for Object. The compiler has to know, at compile time (not at run time) that your object ob has an mInner method, and it can't tell that if the only thing it knows is that it's an Object. By changing it to AnInterface, the compiler now knows that it has an mInner() method.
The scoping rules of a local class are pretty much the same as the scoping rules of a variable, that is, it is confined to the enclosing block.
The same way you cannot access variable iob from main, you cannot access local class Inner from main.
Outside the enclosing block, there's no difference between a local class and an anonymous class. Neither can be accessed. The difference is that within the enclosing block, the local class can be accessed by name, especially useful if you need to access it repeatedly, e.g. to create multiple instances.
The only way to interact with a local/anonymous class outside the enclosing block, is through any superclass or interface implemented by the class in question.
To access the inner class create an object of inner class..
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
from your example
outer t=new outer();
outer.inner inner1=t.new inner();
Hope this helps you...
I'm struggling on the concept of static vs. non-static. I'm studying this Thread example program(modified, from here originally), and when I use inner classes I will get the error:
Error: non-static variable this cannot be referenced from a static context
Here is the error-causing code:
public class Main2 {
public static void main(String[] args) {
Thread simple = new Thread(new SimpleTask());
simple.start();
}
class SimpleTask implements Runnable {
public void run() {
}
;
}
class DaemonTask implements Runnable {
public void run() {
int i = 0;
}
}
}
However, when I break it out so that it's 3 classes, there's no error.. ie if I make it:
public class Main2 {
/* contents */
}
class SimpleTask implements Runnable {
/* contents */
}
class DaemonTask implements Runnable {
/* contents */
}
Then it compiles just fine. Why does it matter that we split it out into another class?
you need an outer class instance(Main2) to access inner class instance(SimpleTask).
Try this:
Thread simple = new Thread(new Main2().new SimpleTask());
Check Inner class on Oracle trails
Because your classes are non-static inner classes; they implicitly need a corresponding instance of the outer class.
Declare your inner classes as static, and your issue should go away.
Try and make class SimpleTask implements Runnable static.
When you declare a class like that, you are declaring somewhat of a per-instance class definition. To be more precise, you are tying the class definition of SimpleTask to an instance of Main2.
In order to instantiate an object of that class you would do:
Main2 obj = new Main2();
SimpleTask t = obj.new SimpleTask();
Notice the use of obj.new. When you call that from inside your outer class, you are really calling this.new. Static methods have no knowledge of this, so you get an error.
SimpleTask and DemonTask class should be static
Instance members(in your case SimpleTask and DemonTask) are associated with the particular object of class.And so you can't use instance members directly within static method(becuase static members don't have any information about the instances of class unless you pass the instance itself as parameter)
You have to either create an object of Main2 and access SimpleTask and DemonTask through it new Main2().new SimpleTask()
OR
make those two classes static
The issue is in the line "Thread simple = new Thread(new SimpleTask());" As the class SimpleTask is defined as a nested class, you need an object of the outer class to create one (the constructor essentially requires an implicit reference to the containing class, similar to how normal methods get an implicit reference to the current class instance as 'this').
What you are essentially asking for here is "Thread simple = new Thread(null.new SimpleTask());" and it's this 'null' which is causing the exception.
Is someone intelligent there who can answer this question?
I m doing some task with following code,
I want to access inner class variable from outer class method.
class Outer extends Activity
{
private Handler mHandler = new Handler();
StopTheThread()
{
mHandler.removeCallbacks(mUpdateTimeTask);// this is the wat i want to do
}
class Inner
{
final Runnable mUpdateTask = new = new Runnable() {
public void run() {
//Some Code Goes Here
}
};
InnerClassMethod()
{
mHandler.removeCallbacks(mUpdateTimeTask);// This statement working fine here
}
}
}
Here mUpdateTask is inner class variable which is not accessible from outer class
Pleas Tell me how can i write that line
You need an instance of Inner to access the mUpdateTask variable.
Something like:
Inner inner = new Inner();
inner.mUpdateTask
// ...
just make the mUpdateTask static ... and call with inner class name.. Inner.mUpdateTask
also you can use getters which will be able to retrun the mUpdatetask.
if you are creating object of this Innerclass i really dont see any point of this question.. you can always call in the way Vivien described above.
Create an Inner class object and then access it
Inner inner = new Inner();
inner.mUpdateTask
// use this
OR
you can create a static mUpdateTask object and can access it using class name
Inner.mUpdateTask
I didn't imagine that I would encounter radically new syntax in Java anymore at this stage, but lo and behold, I just encountered something:
The exact context and what the code below should do is pretty irrelevant - it's there just to give some kind of context.
I'm trying to synthetically create an event in IT Mill Toolkit, so I wrote this kind of line:
buttonClick(new Button.ClickEvent(button));
But, Eclipse gives me the following error message:
No enclosing instance of type Button is accessible. Must qualify the allocation with an enclosing instance of type Button (e.g. x.new A() where x is an instance of Button).
When I rewrite the line above as follows, it doesn't complain anymore:
buttonClick(button.new ClickEvent(button)); // button instanceof Button
So, my question is: What does the latter syntax mean, exactly, and why doesn't the first snippet work? What is Java complaining about, and what's it doing in the second version?
Background info: Both Button and Button.ClickEvent are non-abstract public classes.
Inner classes (like Button.ClickEvent) need a reference to an instance of the outer class (Button).
That syntax creates a new instance of Button.ClickEvent with its outer class reference set to the value of button.
Here's an example - ignore the lack of encapsulation etc, it's just for the purposes of demonstration:
class Outer
{
String name;
class Inner
{
void sayHi()
{
System.out.println("Outer name = " + name);
}
}
}
public class Test
{
public static void main(String[] args)
{
Outer outer = new Outer();
outer.name = "Fred";
Outer.Inner inner = outer.new Inner();
inner.sayHi();
}
}
See section 8.1.3 of the spec for more about inner classes and enclosing instances.
Button.ClickEvent is a non-static inner class so an instance of this class can only exist enclosed in a instance of Button.
In your second code example you have an instance of Button and you create an instance of ClickEvent enclosed in this Button instance...
A non-static inner class in Java contains a hidden reference that points to an instance of the outer class it is declared in. So the error message you got originally is telling you that you cannot create a new instance of the inner class without also specifying an instance of the outer class for it to be attached to.
Perhaps the reason you haven't seen that syntax before is that inner classes are often allocated in a method of the outer class, where the compiler takes care of this automatically.
To avoid confusing yourself and fellow programmers with this rarely-used feature you can always make inner classes static.
In case a reference to the outer class is needed you can pass it explicitly in the constructor.
You actually can do that, but you have to declare ClickEvent as static inside Button, and then you shouldn't have any problem using you sintax:
buttonClick(new Button.ClickEvent(button));
Basically static makes the class ClickEvent belong directly to the class Button instead of a specific instance(i.e. new Button()) of Button.
Following #Jon Skeet example:
// Button.java
class Button
{
public static class ClickEvent
{
public ClickEvent(Button b)
{
System.out.println("Instance: " + this.toString());
}
}
}
// Test.java
public class Test
{
public static void main(String[] args)
{
Button button = new Button();
buttonClick(new Button.ClickEvent(button));
}
public static void buttonClick (Button.ClickEvent ce) {
}
}
Your code would compile, had you typed
buttonClick(new Button().ClickEvent(button));
instead of
buttonClick(new Button.ClickEvent(button));
as a constructor is a method and when you call a method in Java you must pass the list of arguments, even when it is empty.
What is the advantage of local classes in Java or in any other language that makes use of this feature?
Here's an example of how an anonymous inner class, a local inner class, and a regular inner class might be present in a program. The example is looking at a myMethod method and a InnerClass class present in MyClass class. For the sake of discussion, those classes will all be implementing the Runnable interface:
public class MyClass
{
public void myMethod()
{
// Anonymous inner class
Runnable r = new Runnable() {
public void run() {}
};
// Local inner class
class LocalClass implements Runnable
{
public void run() {}
}
}
// ... //
// Inner class
class InnerClass implements Runnable
{
public void run() {}
}
}
The anonymous inner class can be used to simply to make an class that implements Runnable without actually having to write out the class and naming it, and as krosenvold mentioned in his post, it is used as a "poor man's closure" in Java.
For example, a very very simple way to start a Thread using an anonymous inner class would be:
new Thread(new Runnable() {
public void run()
{
// do stuff
}
}).start();
An local inner class can be used to make a class that is within the local scope -- it won't be able to be accessed from other methods outside of myMethod.
If there was another method and we tried to make an instance of the LocalClass that is located inside the myMethod method, we won't be able to do so:
public void anotherMethod()
{
// LocalClass is out of scope, so it won't be found,
// therefore can't instantiate.
new Thread(new LocalClass()).start();
}
An inner class is part of the class that the inner class is located in. So, for example, the inner class InnerClass can be accessed from other classes by MyClass.InnerClass. Of course, it also means that another method in MyClass can instantiate an inner class as well.
public void anotherMethod()
{
// InnerClass is part of this MyClass. Perfectly instantiable.
new Thread(new InnerClass()).start();
}
Another thing about the anonymous inner class and local inner class is that it will be able to access final variables which are declared in the myMethod:
public void myMethod()
{
// Variable to access from anonymous and local inner classes.
final int myNumber = 42;
// Anonymous inner class
Runnable r = new Runnable() {
public void run()
{
System.out.println(myNumber); // Works
}
};
// Local inner class
class LocalClass implements Runnable
{
public void run()
{
System.out.println(myNumber); // Works
}
}
// ... //
So, what are the advantages? Using anonymous inner classes and local inner classes instead of having a separate full-blown inner class or class will allow the former to have access to final variables in the method in which they are declared, and at the same time, the classes are local to the method itself, so it can't be accessed from outside classes and other methods within the same class.
There are a number of things that you can do with local classes that you don't get with anonymous inner classes.
because the type has a name, you can more usefully add members not in the supertype
a given name can make stack traces easier to follow (particularly for lock objects)
subtype more than one base type
construct in more than one place, and multiple constructors
On the other hand they make some hideously verbose syntax even messier.
They allow you to take logic out of the parent class and objectify it. This removes functionality from where it doesn't belong and puts it into its own class. But what if this new object is only needed for a short time, only for the duration of a single block of code? Well, that's where a local class fits in.