I have the following problem. Two nested anonymous types. I want to access "this" reference of the outer anonymous class inside the most inner class. Usually if one has anonymous nested class in a named outer class (lets call it "class Outer") he/she would type inside the nested class Outer.this.someMethod(). How do I refer the outer class if it's anonymous ?
Example Code:
public interface Outer {
void outerMethod();
}
public interface Inner {
void innerMethod();
}
...
public static void main(String[] args) {
...
new Outer() {
public void outerMethod() {
new Inner() {
public void innerMethod() {
Outer.this.hashCode(); // this does not work
} // innerMethod
}; // Inner
} // outerMethod
}; // Outer
...
} // main
The error I get is
No enclosing instance of the type Outer is accessible in scope
I know that I can copy the reference like this:
final Outer outerThisCopy = this;
just before instantiating the Inner object and then refer to this variable. The real goal is that I want to compare the hashCodes of outerThisCopy and the object accessed inside the new Inner object (i.e the Outer.this) for debugging purposes. I have some good arguments to think that this two objects are different (in my case).
[Context: The argument is that calling a getter implemented in the "Outer" class which is not shadowed in the "Inner" class returns different objects]
Any ideas how do I access the "this" reference of the enclosing anonymous type ?
Thank you.
You cannot access an instance of anonymous class directly from inner class or another anonymous class inside it, since the anonymous class doesn't have a name. However, you can get a reference to the outer class via a method:
new Outer()
{
public Outer getOuter()
{
return this;
}
public void outerMethod()
{
new Inner()
{
public void innerMethod()
{
getOuter().hashCode();
}
};
}
};
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...
How do you create an inner class object with reflection? Both Inner and Outer classes have default constructors that take no parameters
Outer class {
Inner class{
}
public void createO() {
Outer.Inner ob = new Inner ();//that works
Inner.class.newInstance(); //<--why does this not compile?
}
}
"If the constructor's declaring class is an inner class in a non-static context, the first argument to the constructor needs to be the enclosing instance; see section 15.9.3 of The Java™ Language Specification."
That means you can never construct an inner class using Class.newInstance; instead, you must use the constructor that takes a single Outer instance. Here's some example code that demonstrates its use:
class Outer {
class Inner {
#Override
public String toString() {
return String.format("#<Inner[%h] outer=%s>", this, Outer.this);
}
}
#Override
public String toString() {
return String.format("#<Outer[%h]>", this);
}
public Inner newInner() {
return new Inner();
}
public Inner newInnerReflect() throws Exception {
return Inner.class.getDeclaredConstructor(Outer.class).newInstance(this);
}
public static void main(String[] args) throws Exception {
Outer outer = new Outer();
System.out.println(outer);
System.out.println(outer.newInner());
System.out.println(outer.newInnerReflect());
System.out.println(outer.new Inner());
System.out.println(Inner.class.getDeclaredConstructor(Outer.class).newInstance(outer));
}
}
(Note that in standard Java terminology, an inner class is always non-static. A static member class is called a nested class.)
Oracle documentation(in below link) says that:
Non-static nested classes (inner classes) have access to other members
of the enclosing class, even if they are declared private.
But in below example I created an object objin (of inner class) and it couldn't access any of the method or variable of its enclosing outer class. Below is the code, could you any one clarify on the same?
http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
package Package_1;
public class Outer {
int k;
public void Multiply()
{
System.out.println("inside outer class' method multiply");
}
public class Inner {
int l;
public void Division()
{
System.out.println("inside inner class' method Divison");
}
}
}
Class with Main method
package Package_1;
public class D {
public static void main(String[] args) {
Outer objout = new Outer();
objout.k = 5;
objout.Multiply();
Outer.Inner objin = objout.new Inner();
objin.l = 7;
objin.Division();
}
}
With objin object I couldn't access that Multiple method in its enclosing class.
I see your "privates"!
From the code of the non-static nested class (inner class) you have access to both public and private members of the enclosing class.
But it's your "privates", not mine!
This is what you're thinking when you try do objin.Multiply(): you are accessing Multiply() as though it's a member of the inner class, but it's not. Remember, you can see it from within the code of the inner class, but it will not be exposed as though it's yours.
This is what the specification says
public class Outer{
private int x;
private void method(){
}
public void publicMethod(){}
public class Inner{
//has access to even private properties of x
method(); //can be called
//NOTE: Only has ACCESS and does not INHERIT those methods
}
}
What you are trying is to access the publicMethod() with the instance of Inner, which does not have any method of that name.
THE CRUX:
The non-static nested classes just has the access to all properties and methods of container class, but does not inherit those methods.
objin.Multiply() cannot work as the crux explains that Multiply() is defined on Outer and not Inner, so there is no method Multiply() on Inner
The documentation doesn't say that you can access to fields and methods of the outer class by using a reference to the inner class. So you can't do
objin.Multiply();
because Multiply is not a method of Inner. What you can do is:
public class Inner {
int l;
public void Division()
{
System.out.println("I can access the field k in outer: " + k);
System.out.println("I can access the method Multiply in outer (even if Multiply was private): ");
Multiply();
// which is a shortcut for
Outer.this.Multiply();
}
}
PS: please respect the Java naming conventions. Methods start with a lowercase letter.
You are trying to access the method by using instance of the Inner class object. It can be accessed outside only by Outer class method. You can call the method inside the class definition of the Inner class directly but not by using the instance of inner class. if you still want to do this try :
package Package_1;
public class Outer {
int k;
public void Multiply()
{
System.out.println("inside outer class' method multiply");
}
public class Inner {
int l;
public void Division()
{
System.out.println("inside inner class' method Divison");
}
public void Multiply() {
Outer.this.Multiply(); //Outer class method.
}
}
}
public class InnerClass {
class Inner
{
public void method()
{
System.out.println("Innerclass");
}
}
}
class Sample extends InnerClass.Inner
{
public static void main(String [] arg)
{
Sample s = new Sample(new InnerClass());
s.method();
}
//why is this mandatory???
Sample(InnerClass i) {
i.super();
}
#Override
public void method() {
System.out.println("derived class");
}
}
when i make a class that derives from an innerclass (Innerclass.Inner) default constructor doesn't works. later i came to know that it requires to include a constructor taking Enclosing class reference why is it so?
Non static inner classes in Java have an implicit reference to the enclosing instance. You can solve your problem with:
public class InnerClass {
static class Inner // can make it public too
{
public void method()
{
System.out.println("Innerclass");
}
}
}
Just don't expect to be able to call any methods on InnerClass without a specific instance.
Because non-static inner classes have an implicit member that points back to their outer class, and you can't create an instance of the inner class without giving it that pointer. If you directly create an instance of an inner class, you have to use new outer.Inner() (or it might be outer.new Inner(), I can never remember). But Sample isn't an inner class, it just inherits one, so the outer instance must be passed in its constructor to the base constructor. Thus, it needs to have some instance of outer available, or create it itself.
I created a non-static inner class like this:
class Sample {
public void sam() {
System.out.println("hi");
}
}
I called it in main method like this:
Sample obj = new Sample();
obj.sam();
It gave a compilation error: non-static cannot be referenced from a static context When I declared the non-static inner class as static, it works. Why is that so?
For a non-static inner class, the compiler automatically adds a hidden reference to the "owner" object instance. When you try to create it from a static method (say, the main method), there is no owning instance. It is like trying to call an instance method from a static method - the compiler won't allow it, because you don't actually have an instance to call.
So the inner class must either itself be static (in which case no owning instance is required), or you only create the inner class instance from within a non-static context.
A non-static inner class has the outer class as an instance variable, which means it can only be instantiated from such an instance of the outer class:
public class Outer{
public class Inner{
}
public void doValidStuff(){
Inner inner = new Inner();
// no problem, I created it from the context of *this*
}
public static void doInvalidStuff(){
Inner inner = new Inner();
// this will fail, as there is no *this* in a static context
}
}
An inner class needs an instance of the outer class, because there is an implicit constructor generated by compiler. However you can get around it like the following:
public class A {
public static void main(String[] args) {
new A(). new B().a();
}
class B {
public void a() {
System.err.println("AAA");
}
}
}
Maybe this will help : http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html
the non-static inner class cannot be called in a static context (in your example there is no instance of the outer class).