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 innerprotected
classInner
. - Class
Inner
has a constructor and a method that isf()
. - Class
A
also has a constructor, a methodg()
that callsf()
method ofInner
and a methodinsertTime(Inner yy)
that gets anInner
object and sets it to its privateInner
attribute. - We have also created a class,
Main
that extendsA
. - It has an inner class
B
that extendsA.Inner
and overridesf()
method ofInner
. Main
class has a constructor where it callsinsertInner(Inner yy)
method ofA
.- We create a new
Main
instance, callg()
method ofMain
and 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.