class
Inherit inner class example
In this example we shall show you how to inherit an inner class. The following steps describe the example:
- We have created class
A, that has an innerprotectedclassInner. - Class
Innerhas a constructor and a method that isf(). - Class
Aalso has a constructor, a methodg()that callsf()method ofInnerand a methodinsertTime(Inner yy)that gets anInnerobject and sets it to its privateInnerattribute. - We have also created a class,
Mainthat extendsA. - It has an inner class
Bthat extendsA.Innerand overridesf()method ofInner. Mainclass has a constructor where it callsinsertInner(Inner yy)method ofA.- We create a new
Maininstance, callg()method ofMainand see what happens,
as described in the code snippet below.
package com.javacodegeeks.snippets.core;
class A {
protected class Inner {
public Inner() {
System.out.println("A.Inner()");
}
public void f() {
System.out.println("A.Inner.f()");
}
}
private Inner y = new Inner();
public A() {
System.out.println("New A()");
}
public void insertInner(Inner yy) {
y = yy;
}
public void g() {
y.f();
}
}
public class Main extends A {
public class B extends A.Inner {
public B() {
System.out.println("Main.B()");
}
@Override
public void f() {
System.out.println("Main.B.f()");
}
}
public Main() {
insertInner(new B());
}
public static void main(String[] args) {
A e2 = new Main();
e2.g();
}
}
Output:
A.Inner()
New A()
A.Inner()
Main.B()
Main.B.f()
This was an example of how to inherit an inner class in Java.
