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 inner protected class Inner.
  • Class Inner has a constructor and a method that is f().
  • Class A also has a constructor, a method g() that calls f() method of Inner and a method insertTime(Inner yy) that gets an Inner object and sets it to its private Inner attribute.
  • We have also created a class, Main that extends A.
  • It has an inner class B that extends A.Inner and overrides f() method of Inner.
  • Main class has a constructor where it calls insertInner(Inner yy) method of A.
  • We create a new Main instance, call g() method of Main 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.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button