Extending inner [nested] classes

OK I've got a class (A) with a nested class (B).
B accesses variables etc. in A and does its own thing, but what I'd like to do is make B abstract and have a number of classes extend it - which is used depends on program arguments.
The problem I'm having is that the new class (C) that extends B does not seem to have access to any of the variables in A.
I originally tried:
class C extends B
and
class C extends A$B
I also tried this, which I found on this site:
class C extends A.B
(thats A-dot-B) but it still doesnt seem to be working.
Is it possible to extend [abstract] inner classes like this? If so, how? Any help appreciated. cheers.

Here I found a solution. However, it is not so elegant. In fact, I am also having trouble in extending a nested class in an elegant way.
Here, A is the original top-level class and A.B is the nested class of A. A2 extends A. B2 and B3 extends A.B. Main is the class where the main() method can be found.
// A.java
public class A {
  private B b;
  public void setB (B b) {
    this.b = b;
  public B getB () {
    return b;
  public abstract class B {
    public abstract String getName();
// A2.java
public class A2 extends A {
  public class B2 extends A.B {
    public String getName () {
      return "Peter";
  public class B3 extends A.B {
    public String getName () {
      return "John";
public class Main {
  public static void main (String[] args) {
    A a = new A2 ();
    A.B b = ((A2)a).new B2 ();
    a.setB (b);
    System.out.println (a.getB().getName());  // John
    b = ((A2)a).new B3 ();
    a.setB (b);
    System.out.println (a.getB().getName());  // Peter
}You may see here that I used "A" as the type of "a". Te reason is I want to use "a" as an "A", not "A2". If you don't want to do casting, you may simply use "A2" as the type. The class A2 can be blank. It is only a "container" of the classes B2 and B3.

Similar Messages

  • Inner/Nested Classes

    Could someone tell me what the rules of accessibility are for static and non-static inner classes being able to access elements of the enclosing class

    A non-static or inner class can access all of the enclosing class's members, including private members. This is because each instance of an inner class is associated with an instance of the outer class, and inner classes are not allowed to have static members except for constants.
    A static nested class can access only the static members of the enclosing class. This is because instances of the nested class are not associated with instances of the outer class.

  • Extending a nested class and parent access

    I want the child of the abstract inner class to have access to the inner classes parent's variables. I know that an inner class can access it's parent's variables and methods with the "[ParentClass].this.[var/method]" syntax. What's the appropriate syntax for the situation I'm describing?
    My setup is like this:
    class Canister {
      int a = 0;
      public abstract class Behavior
    class Lonely Behavior extends Behavior
      public int getParentVariable() {
        return Canister.this.a;
    }Thanks!
    -stephen

    The correction to my code is:
    class Canister
      int a = 0;
      public abstract class Behavior
    class LonelyBehavior extends Canister.Behavior
      public int getParentVariable() {
        return Canister.this.a;
    }The compiler doesn't have a problem with me extending Canister.Behavior because it's public inside of Canister. But as I explained, the "[ParentClass].this.[var/method]" syntax doesn't work.
    This is inconsistent with inheritance: you'd think that if you extend an inner class, you would inherit the abilities and characteristics of that inner class, just as you would in other cases of inheritance. It's also inconvenient: if the inner class is abstract because you want programmers to extend and upgrade it, those programmers have to change the source code of the enclosing class to include the new classes.
    Anyway, thanks for the info.

  • Inner Class extending the outer class

    Could anyone explain this code to me? It can compile and run. Could anyone tell me what the class Main.Inner.Inner is? What members does it consists of? How the compiler manage to build such a class?
    public class Main {
        public static class Inner extends Main {
        public static void main(String[] args) {
            System.out.println("Hello, world.");
    }

    By the way, it's not really an inner class, because it's static. It's just a nested class.
    You might want to have a nested class extend its enclosing class if, maybe, you wanted to delegate to subclasses and didn't want to create a lot of extra source code files, which might make sense if the nested subclasses were really small.
    public abstract class Animal {
      public abstract void makeSound();
      private Animal() {} // can't be directly instantiated
      private static class Dog extends Animal {
        public void makeSound() { System.out.println("woof"); }
      private static class Cat extends Animal {
        public void makeSound() { System.out.println("meow"); }
      private static class Zebra extends Animal {
        public void makeSound() { System.out.println("i am a zebra"); }
      public static Animal get(String desc) {
        if ("fetches sticks".equals(desc)) {
          return new Dog();
        if ("hunts mice".equals(desc)) {
          return new Cat();
        if ("stripey horse".equals(desc)) {
          return new Zebra();
        return null;
    public class AnimalTest {
      public static void main(String... argv) {
        Animal a = Animal.get("fetches sticks");
        a.makeSound();
    }

  • When to use Nested Class/Inner Classes ?

    I am not very clear, when to use nested/inner classes..
    The scenario is :-
    class ABC
    //ABC need to store multiple instance of class XYZ
    class XYZ
    int member1;
    int member2;
    One approach is
    class ABC
    class XYZ
    //vector of class XYZ instances is stored in class-ABC
    or another approach is Class XYZ can be in separate JAVA file.
    Query:-
    1) Is there any difference between nested or Inner class...or are they same?
    2) When should they be used....Is it good to use in above scenario.
    3) What are the disadvtanges/advantages of using the Nested
    class.

    Query:-
    1) Is there any difference between nested or Inner
    class...or are they same?I really don't get it. Yes there is a difference between having an inner class, and a class in a separate file, but a nested class is an inner class.
    2) When should they be used....Is it good to use in
    above scenario.To write an inner class is a design decision. Do other classes need to know about the class XYZ or not? Do the XYZ class need to know about the inner working of the ABC class? How complex is the XYZ class etc.
    >
    3) What are the disadvtanges/advantages of using the
    Nested
    class.See above.
    /Kaj

  • Referencing an inner swingworker class in a JPanel class...?

    Hi,
    I've got an inner swingworker class defined inside an extended JPanel (we'll call it middleJ) class. Basically the swingworker class runs off a filtered file chooser. I have a method in the JPanel class that instantiates the inner class and kicks off the swing worker (we'll call it kickOffSwing). Now if I instantiate middleJ in an outer class and call the kickOffSwing() method, that should run the filtered filechooser right? Is this the right way to go about running a lengthy background process inside a nested class structure, or is there a more organised way of doing things?
    Cheers!

    Never mind. Got it working fine! I often find the act of putting together a question helps focus on the task at hnad.

  • Instantiating a nested class from JNI

    Im able to instantiate my public member class "Inner" as long as the constructor does not take any arguments. If it requires arguments in the constructor, I get a crash report. I need to be able to instantiate the object with supplied initial arguments. Is this a bug in the JVM? Any suggestions?
    /dan
    Crash report follows after code:
    class HelloWorld {
       public class Inner {
          private int myValue = 50;
          public Inner() {}
          public Inner(int myValue) {
             this.myValue = myValue;
          public Inner(int myValue, int there) {
             this.myValue = myValue;
    }C++ library:
       jclass inr_clz = env->FindClass("LHelloWorld$Inner;");
       if (inr_clz == NULL) {
          return -25;               // failed to find the class
    //   mid = env->GetMethodID(inr_clz, "<init>", "(LHelloWorld;)V");              // works
       mid = env->GetMethodID(inr_clz, "<init>", "(LHelloWorld;II)V");            // also works
       if (mid == NULL) {
          return -30;                    // failed to get method
       jint value = 400;
    //   inner = env->NewObject(inr_clz, mid);                           // works
       inner = env->NewObject(inr_clz, mid, value, value);             // crash here
       if (inner == NULL) {
          return -40;                     // out of memory error
       ...Crash message:
    # An unexpected error has been detected by HotSpot Virtual Machine:
    # Internal Error (53484152454432554E54494D450E43505001A3), pid=2008, tid=2628
    # Java VM: Java HotSpot(TM) Client VM (1.5.0_06-b05 mixed mode)
    # An error report file with more information is saved as hs_err_pid2008.log
    # If you would like to submit a bug report, please visit:
    # http://java.sun.com/webapps/bugreport/crash.jsp
    #

    Im able to instantiate my public member class "Inner"
    as long as the constructor does not take any
    arguments. If it requires arguments in the
    constructor, I get a crash report. I need to be able
    to instantiate the object with supplied initial
    arguments. Is this a bug in the JVM? Any
    suggestions?It's your code.
    Here's a working example:
    ==================
    public class NativeInnerTest {
         public static void main(String[] args) {
              new Outer().doNative();
    public class Outer {
         static {
              System.loadLibrary("outer");
         public class Inner {
              private int val;
              Inner (int val) {
                   this.val = val;
              public void foo() {
                   System.out.println("Value is: " + val);
         public native void doNative();
    }=====Native Code======================
    #include "Outer.h"
    JNIEXPORT void JNICALL Java_Outer_doNative (JNIEnv *env, jobject obj) {
         jclass clz = env->FindClass("Outer$Inner");
         if (clz == NULL) {
              printf("Failed to find class Outer$Inner");
              return;
         jmethodID mid = env->GetMethodID(clz,"<init>", "(LOuter;I)V");
         if (mid == NULL) {
              printf ("Failed to find Inner constructor\n");
              return;
         jint val = 42;
         jobject inner = env->NewObject(clz,mid,obj,val);
         if (inner == NULL) {
              printf ("Failed to construct Inner object\n");
              return;
         jmethodID fooID = env->GetMethodID(clz, "foo", "()V");
         if (fooID ==  NULL) {
              printf ("Failed to find method id for foo()\n");
              return;
         env->CallVoidMethod(inner, fooID);
    }================================
    The problem in your code is twofold. First, your type signature in the call to GetMethodID is incorrect. An inner class constructor taking a single integer argument should have a type signature like this:
    (LHelloWorld;I)V
    You can get the proper type signatures using the 'javap' tool. For my example, the output of javap looks like this:
    [jim@daisy tmp]$ /usr/java/jdk1.6.0/bin/javap -s -private Outer.Inner
    Compiled from "Outer.java"
    public class Outer$Inner extends java.lang.Object{
    private int val;
      Signature: I
    final Outer this$0;
      Signature: LOuter;
    Outer$Inner(Outer, int);
      Signature: (LOuter;I)V
    public void foo();
      Signature: ()V
    }Second, your call to NewObject does not have the proper parameter types. Here's your code:
    inner = env->NewObject(inr_clz, mid, value, value);The corresponding correct line from my example is:
    jobject inner = env->NewObject(clz,mid,obj,val);The constructor expects a 'HelloWorld' object and an integer as denoted in the correct
    type signature.
    You are passing in the integer 'val' twice when you should be doing something like this:
    inner = env->NewObject(inr_clz, mid, obj, value);where 'obj' is the jobject passed to you by the VM along with the JNIEnv pointer. This jobject represents the instance of the enclosing class which every non static nested class must have.
    Jim S.

  • Help with the above program .. Nested Classes

    class Outer {
         Outer() {
              System.out.println("Global Outer");
    Class Main {
         //Nested Class by default extends the local class Outer
         Class Inner extents Outer {
              Inner() {
                   super();
                   System.out.println("Inner");
         //Local class Outer
         Class Outer {
              Outer() {
                   System.out.println("Local Outer");
         //Main function
         public static void main(String[] args) {
              new Main().new Inner();
    /* Output will be
    * Local Outer
    * Inner
    /* I want to extend the Global Outer Class by Inner .. how do i do this */

    This is not one of those stupid exam questions ....
    I was just curious .....
    I could have simply added a package statement at the start
    package mypack;Then extended the outer class by the foll statement
    class NestedClass extends mypack.Outer {
                     // declarations and definitions
    }I was just curious whether it was possible without the package statement
    Thanks a lot guys!

  • How to override a nested class?

    I'm relatively new to Java, so this may be an easy question, but how do you override the behaviour of a nested class when extending a parent class? For example:
    public class MyParentClass
      public class MyParentNestedClass
        public void someMethod()
          // Some functionality that I want to change 
    }Now I want to create a new class, let's call it MyChildClass, which extends MyParentClass and changes the behaviour of the inner class. Is this possible? What is the syntax to accomplish this? Are there any scope-related problems I should be aware of?
    Do I have to extend the parent class in order to redefine the nested class, or is there some way to just override the nested class (which is all I really want to change)? Any help on this would be appreciated, I've searched both the Sun site and Google and can't come up with a really clear answer to this one.
    Thanks,
    Steve

    That's exactly what I was after. I was trying to do it like this:
    public class MyChildClass extends MyParentClass
      MyParentNestedClass childNestedClass = new MyParentNestedClass()
        public void someMethod() { /* new functionality */ }
    }because I have seen anonymous classes (I think they're called adapter classes) declared like this, but it wasn't working in this case. Thanks for showing me the correct way to do it, I guess in retrospect that makes perfect sense, I don't know why I didn't think of it.
    Thanks,
    Steve

  • Interface having nested class

    Suppose an interface happens to have an inner class or nested class inside its definition.
    If a class implements this particular interface, will this class have acess to the methods of
    nested class in the interface, OR will this class only have access to the methods in the interface.

    It could make sense for an interface to define a nested exception type to be thrown by one of its methods.
    E.g.
    interface MyInterface {
        void handleSomething(...) throws OopsException;
        class OopsException extends Exception { }
    }This is the only circumstance I recall where I've defined a nested class in an interface. When all implementations of the interface are supposed to use this exception type, and it's not supposed to be thrown from anywhere else, it just made more sense in terms of naming and scoping than making the exception a top level class.

  • Nested Classes and Static Methods

    I was perusing the Java Tutorials on Nested Classes and I came across this...
    [http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html|http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html]
    I was reading the documentation and I read a slightly confusing statement. I was hoping some further discussion could clarify the matter. The documentation on "Nested Classes" says (I highlighted the two statements, in bold, I am having trouble piecing together.)
    Static Nested Classes
    As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class ? it can use them only through an object reference.
    Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
    So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?

    So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?No, it means that a static nested class cannot refer to instance variables of its enclosing class. Example:public class Foo {
        int i;
        static class Bar {
            int j = i; // WRONG! Bar class is static context
    }~

  • Nested classes and separate files in Javadoc...

    Hello. I am writing an application, and it has several .java files, and some of the classes contained therein contain nested classes, for example
    ClassOne.java
    class ClassOne
    // stuff
       class innerClassOne
          //more stuff
    }ClassTwo.java
    class ClassTwo
    // stuff
       class innerClassTwo
          //more stuff
    }What I want to do is generate documentation like the online java documentation for my app, that is, documentation that will contain ALL the classes and nested classes involved, and link everything that comes in java already to the sun online java docs.
    I've figured out the -link command for javadoc, and I can make that work, but I've run into some other snags.
    1.) Javadoc isn't finding or documenting my nested classes, despite them being marked up. Google does not wish to help.
    2.) Some classes reference other classes of mine that aren't conatined in the same .java file, but do exist in their own .java files in the dame local directory. Javadoc does not like this, and gives errors.
    3.) Running javadoc on one file at a time overwrites the old file's documentation, thus I cannot seem to get an index.html javadoc file that links to all my classes, nor can I get the classes to link to each other.
    What do I need to do to fix these?

    So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?No, it means that a static nested class cannot refer to instance variables of its enclosing class. Example:public class Foo {
        int i;
        static class Bar {
            int j = i; // WRONG! Bar class is static context
    }~

  • JDWP reference implementation does not return anonymous nested classes?

    Using
    $ java -version
    java version "1.6.0_22"
    Java(TM) SE Runtime Environment (build 1.6.0_22-b04)
    Java HotSpot(TM) Client VM (build 17.1-b03, mixed mode, sharing)
    it appears that when I connect with JDWP and issue a NestedTypes command, the result does not include anonymous nested types. The only references to this that I could find is a comment in a svn commit at apache (http://mail-archives.apache.org/mod_mbox/harmony-commits/200611.mbox/%[email protected]%3E)
    Is this intentional and desired? Is there a way to get all of the nested types, including the anonymous ones? I could do ClassesBySignature with "package.ClassName$*" as the signature and filter out doubly nested classes, but that seems overly complicated.

    exept, you can NOT have an implementation of an
    abstract class (which foundPlugin) is without an
    implementation of all it's subclasses (such as
    argsObject) You're mistaken in a couple of ways here.
    First, a nested class is not the same as a subclass.
    Second, a concrete class must have implementations for all its methods, but it can still have an abstract nested class.
    Third, you can have an instance of a concrete class that has abstract subclasses. Object is concrete and has many concrete subclasses. Classes don't know anything about their subclasses.
    This compiles.
    public abstract class AbOut {
      public abstract class AbIn {  public abstract void bar(); }
    public class ConcOut extends AbOut {
      public abstract class AbIn2 { public abstract void foo();}
    foundPlugin MUST have an implementation
    of argsObject, according to the rules of java,And you think this because...?
    You read it in the JLS? Citation please.
    You tried to compile and it failed? My sample above demonstrates the countereample. If I'm misunderstanding what you're talking about, please post an example
    Or maybe you just thought it had to be that way because that seemed the most intuitive and when it wasn't, rather than trying to understand or adjust your thinking, you figured it would be more fun to throw a hissy fit and call Java "stupid"?

  • Question about nested classes

    Hi, i currently have the following problem:
    I have 2 classes, one of which also has a nested class:
    1. Home.java (extends JApplet)
    2. Away.java (extends JPanel) has nested class, private class ButtonListener implements ActionListener
    Now in Home.java I have a Vector ( called bankaccount) which i pass to the Constructor of Away.java ( I declared the vector again there as an instance by Private Vector bankaccount;).
    My problem is that in ButtonListener I am trying to access the Vector so that i can modify it when a button has been clicked, and i thought i could just use the commands of bankaccount.add() and bankaccount.get() directly, however it seems like ButtonListener cannot access the Vector, even though i passed it along to the Constructor of the Away class.
    Any suggestions on how i get access the Vector from the ButtonListenere class?

    This is an example:
    public class Home extends JApplet
    private Away away;
    private Vector bankaccount;
    public void init()
         bankaccount = new Vector();
         away = new Away(bankaccount);
    public class Away extends JPanel
    private Vector bankaccount;
    JTextArea text1= new JTextArea(50,50);
    public Away(Vector bankaccount)
       //declare buttons,textarea,setLayout,etc
    button1.addActionListener (new ButtonListener());
    //i can set  text1.setText(( String)bankaccount.get(0));
    // here to access bankaccount, and it shows up fine, but i want
    // do it in from the class below
    private class ButtonListener implements ActionListener
              public void actionPerformed(ActionEvent event)
                         //trying to access bankaccount here by doing:
                        // but it is not doing anything
                        text1.setText(( String)bankaccount.get(0));
    }

  • Questions concerning Nested Classes

    Hi!
    Just read some articles about nested classes (include the ones from the Java Tutorial and the Effective Java chapter), and while most of it is perfectly clear, three questions remain:
    1.) When I declare a member class, how should I declare the access specifiers (private, protected etc.) for the member class's attributes and methods? If I declare a member class as private, anything but private for the attributes and methods wouldn't make sense, would it?
    2.) The Java Tutorial says:
    Also, because an inner class is associated with an instance, it cannot define any static members itself.While this is true for static methods, it seems to be possible to declare static variables inside inner classes. This is confusing me... does it actually make sense to declare static variables inside inner classes (or member classes in general)? Or should the be placed in the declaring class?
    3.) Another confusing quote from the Java Tutorial:
    Static nested classes do not have access to other members of the enclosing class.This is true for instance variables and methods but not for static variables, which are also members of the enclosing class, aren't they?
    Thanks in advance,
    OIiver

    Trollhorn wrote:
    Hi!
    Just read some articles about nested classes (include the ones from the Java Tutorial and the Effective Java chapter), and while most of it is perfectly clear, three questions remain:
    1.) When I declare a member class, how should I declare the access specifiers (private, protected etc.) for the member class's attributes and methods? If I declare a member class as private, anything but private for the attributes and methods wouldn't make sense, would it?
        private static class MyInner implements Runnable
            @Override public void run() // Must be public!
    2.) The Java Tutorial says:
    Also, because an inner class is associated with an instance, it cannot define any static members itself.While this is true for static methods, it seems to be possible to declare static variables inside inner classes. This is confusing me... does it actually make sense to declare static variables inside inner classes (or member classes in general)? Or should the be placed in the declaring class?Wrong. It can define static final member variables and I see no reason to move them to the outer class, if they are used only by the inner class.
    3.) Another confusing quote from the Java Tutorial:
    Static nested classes do not have access to other members of the enclosing class.This is true for instance variables and methods but not for static variables, which are also members of the enclosing class, aren't they?I agree with you here.
    Edited by: baftos on Jun 6, 2009 9:18 AM

Maybe you are looking for