Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two questions on inner classes in Java (class A { class B { } })

Tags:

java

class

Sorry for the bad title, but I couldn't think of a better one.

I'm having a class A and a class B which is kind of a sub class of A, like so:

(Is there actually a correct name for it? Isn't "sub class" reserved for inheritance?)

class A {
    int i = 0;
    class B {
        int j = 1;
    }
}

class Test {
    public static void main() {
        A a = new A();
        B b = a.new B();
        A c = ??? b ??? // get "a" back
    }
}

From B every property of A can be accessed, therefore both, a.i and b.i, return 0. Now, I'm wondering whether it's somehow possible to retrieve the original object of type A out of b, as b contains everything that a contains? Simple casting apparently doesn't do the trick.

Second one:

class A {

    void print() {
        System.out.println("This is class A.");
    }

    class B {
        void print() {
            // <--- How to access print() of class A (like this.A.print() or smth)? 
            System.out.println("This is class B.");
        }
    }
}

You could alternatively also provide me with some good resources on this topic, as I've been too stupid to find a good one so far.

Thanks in advance. :)

like image 488
balu Avatar asked Dec 04 '08 00:12

balu


2 Answers

There doesn't seem to be a way to access the outer class from outside. But you can do it like this:

class A {
    int i = 0;
    class B {
        final A outer = A.this;
        int j = 1;
    }
}

class Test {
    public static void main() {
        A a = new A();
        A.B b = a.new B();
        A c = b.outer // get "a" back
    }
}

ClassName.this will be the instance of the outerclass associated with the instance of an inner class.

like image 81
Johannes Schaub - litb Avatar answered Oct 11 '22 12:10

Johannes Schaub - litb


You can access it with the ParentClass.this syntax from within the inner class.

e.g.

public class Outter
{
    class Inner {
        public Outter getOutter()
        {
            return Outter.this;
        }
    }

    public Inner getInner(){
        return new Inner();
    }
}

class Runner{
    public static void main(String[] args){
        Outter out = new Outter(); 
        Outter.Inner inner = out.getInner();

        System.out.println(inner.getOutter().toString());
    }
}
like image 35
madlep Avatar answered Oct 11 '22 14:10

madlep