Why a nested class can instantiate an abstract class?

Hi people!
I'm studying for a SCJP 6, and i encountered this question that i can figure it out but i don't find any official information of my guess.
I have the following code:
public class W7TESTOQ2 {
    public static void main(String[] args) {
       // dodo dodo1 = new dodo();
        dodo dodo2 =new dodo(){public String get(){return "filan";}};
        dodo.brain b = dodo2.new brain(){public String get(){return "stored ";}};
        System.out.print(dodo2.get()+" ");
        System.out.println(b.get());
abstract class dodo
    public String get()
        return "poll";
    abstract class brain
        public abstract String get();
}I know that abstract classes cannot be instantiated but i see that in this example, with a nested anonymous class it does (dodo and brain classes). My guess is that declaring the nested class it makes a subclass of the abstract class and doing so it can be instantiated. But i can't find any documentation about this.
Does anybody know?
Really thanks in advance.
Regards,
Christian Vielma

cvielma wrote:
Another question about this. Why can't i declare a constructor in the nested class? (it gives me return type required)You cannot declare a constructor, because in one line you're declaring a new class (the anonymous inner class) as well as constructing an instance of it.
What you can do, however, is if the abstract class (or the superclass, in any case, it doesn't need to be abstract) defines several constructors, you can call them.
public abstract MyClass {
    public MyClass() {
        // Default do nothing constructor
    public MyClass(String s) {
        // Another constructor
// Elsewhere
MyClass myclass = new MyClass("Calling the string constructor") {
};But you can't define your own constructors in the anonymous inner class.
Also, since the class is anonymous, what would you name the constructor? :)
Edited by: Kayaman on 26.6.2010 22:37

Similar Messages

  • Why Use Nested Classes

    Hi All,
    Why do we use Nested Classes ? Explain it with example ....
    If we say - It is a way of logically grouping classes that are only used in one place. Then we can say we use it through "Package" so why inner class ??
    Thanks in advance ....

    A real life example to jschell's explaination may be this.
    The pistons in your automobile engine are encapsulated by the engine block -- or the engine block encapsulates the pistons inside. This is the desired effect because as soon as we take the pistons out of the engine block, and put them say, in the backseat of the car instead, they no longer perform the function they were intended. There is another side effect to this analogy. When the pistons are properly installed in the engine block, there is only one movement the pistons can move -- up and down movement, that's it... they cannot rotate, spin, twist around or anything inside the engin block. Furthermore, the up and down movement is the only useful thing a piston can do. As soon as we throw the pistons in the backseat of the car, they can roll around, spin, and generally rotate to any configuration or orientation -- which does not produce any useful power.
    Inner classes are generally the same way. So we can see this example with a little code -- which we like.
    public class Engine
      Piston[] pistons = new Piston[8];
      class Piston
        // the usual methods here..
    }Of course, if your program is extremely sohisticated, this may not be a good solution -- for example, if you are making a catalog of automotive parts, then you would probably want your <tt>Piston</tt> class to be stand-alone.
    Edited by: pierrot_2. Also notice that the class <tt>Piston</tt> is not an INNER class of Backseat!

  • Why a static class can implements a non-static interface?

    public class Test {
         interface II {
              public void foo();
         static class Impl implements II {
              public void foo() {
                   System.out.println("foo");
    }Why a static class can implements a non-static interface?
    In my mind, static members cann't "use" non-static members.

    Why a static class can implements a
    non-static interface?There's no such thing as a non-static member interface. They are always static even if you don't declare them as such.
    An interface defines, well, a public interface to be implemented. It doesn't matter whether it is implemented by a static nested class or by an inner class (or by any class at all). It wouldn't make sense to enforce that it should be one or the other, since the difference between a static and non-static class is surely an irrelevant detail to the client code of the interface.
    In my mind, static members cann't "use" non-static
    members.
    http://java.sun.com/docs/books/jls/third_edition/html/classes.html#246026
    Member interfaces are always implicitly static. It is permitted but not required for the declaration of a member interface to explicitly list the static modifier.

  • Can interface extend abstract class?

    Can interface extend abstract class?
    I tried to make a interface extend an abstract class but i got an error stating:
    interface expected here.
    Can anyone help me ?

    > ok, but can an interface implement an abstract class?
    No. An interface provides no implementation whatsoever. An abstract class can implement an interface, but not the other way around.
    http://java.sun.com/docs/books/tutorial/java/concepts/interface.html
    ~

  • Why a static nested class instead of a static block?

    What difference does it make: using a static nested class on a static block?

    Surya-2010 wrote:
    What difference does it make: using a static nested class on a static block?Do you mean static initialization block?
    They're different concepts. A static initialization block is part of the construction machinery of a class. A static nested class is a class you want to treat as part of another class.

  • Question about the property of the nested class.

    "Nested classes may be declared static. In this case, the nested class has no reference to an enclosing instance"
    Can any one demonstrate the above through an code example?? thanks

    thanks jverd.
    Then why dont you answer my other thread??You have several threads. I've said what I have tosay in all the ones that I know about, am interested
    in, and have the time to answer. Last one I lookedat, you were in Monica's very capable hands, so I had
    nothing to add.
    Thanks!I may not be the sharpest knife in the drawer, but I know better than to piss of her what's gonna administer the dread Blueberry Pie Torture.

  • Nested Classes in Labview 8.2

    hello everyone,
    I am a 'measurement studio' convert to labview, so I have been getting my head around the 'object oriented programming' features of labview 8.2. There seems to be many things lacking in this implementation, like Java/C# style interfaces, and abstract classes.
    Also I haven't found a way to create a nested class (so a class within a class). Is this possible in Labview 8.2 or 8.5?
    Thanks,
    paul

    I just stumbled across this post looking for other information......
    Is it true that nested classes are not supported?
    I just tried this out and it seemed to work for me.  Can we add a class as a data member of another class?  I think I recall this even being propagated in an article, but I can't remember which.
    I think it was about an object referencing itself in it's own data field to create a recursive object call.....
    Can someone please confirm that nested classes are supported and working?  Which caveats need to be observed?  I'm just starting working on something which kind of relies on the ability to nest classes, so I'm quite interested as to whether it's feasible or not.
    I'm using LV 8.2.1.
    Shane.
    Using LV 6.1 and 8.2.1 on W2k (SP4) and WXP (SP2)

  • 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"?

  • Incorrect ClassDoc for nested classes

    Hello,
    I think there is a bug in Javadoc concerning nested classes ClassDoc records extracted through the doclet API.
    In particular, ClassDoc records are correct if the container class is directly specified on the command line as a .java file or part of a package (i.e. the source is available), but they are (at times) wrong if the records are built from .jar (.class) files through the classpath.
    Example with "java.io.ObjectOutputStream" from JDK 1.3.1_01:
    If the ClassDoc for this class comes from RootDoc.specifiedClasses(), its nested classes are correctly listed as:
    private static final class java.io.ObjectOutputStream.HandleTable
    public abstract static class java.io.ObjectOutputStream.PutField
    static final class java.io.ObjectOutputStream.PutFieldImpl
    private static final class java.io.ObjectOutputStream.ReplaceTable
    private static final class java.io.ObjectOutputStream.Stack
    but if the ClassDoc of the container class is extracted from a method parameter, like in org.apache.xerces.dom.ParentNode.writeObject(ObjectOutputStream out), this is the result:
    final synchronized class java.io.ObjectOutputStream$HandleTable
    public abstract static class java.io.ObjectOutputStream.PutField
    static final class java.io.ObjectOutputStream.PutFieldImpl
    final synchronized class java.io.ObjectOutputStream$ReplaceTable
    final synchronized class java.io.ObjectOutputStream$Stack
    According to my tests, at least ClassDoc.modifiers(), ClassDoc.qualifiedName() and ClassDoc.containingClass() return incorrect results for HandleTable, ReplaceTable and Stack.
    This behaviour seems common to both Javadoc 1.3.1_01 and 1.4beta3. I admit I didn't test 1.4 final, but I searched the Javadoc site, the forum and the bug database without finding anything similar.
    Thanks in advance for any help.
    Amedeo Farello

    Thank you for looking into this.
    This is beyond my understanding of the Doclet API.
    Please submit this as a bug using the instructions at:
    http://java.sun.com/j2se/javadoc/faq/index.html#submitbugs
    and please email the ID number you get back to me
    at [email protected] so I can make sure it gets
    past our initial reviewers and into our bug database so
    our javadoc engineer can look at it.
    -Doug Kramer
    Javadoc team

  • 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.

  • Tutorial Q&E : Implementing Nested Classes, Question 2

    //1.3
    Taken from http://java.sun.com/docs/books/tutorial/java/javaOO/QandE/nested-answers.html
    import java.util.*;
    public class Problem {
    public static void main(String[] args) {
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
    public void run() {
    System.out.println("Exiting.");
    timer.cancel();
    5000);
    System.out.println("In 5 seconds this application will exit. ");
    Question 2: The program Problem.java (above) doesn't compile. What do you need to do to make it compile? Why?
    Answer 2: Add final in front of the declaration of the timer variable. A nested class declared within a method has access to any final, local variables in scope.
    Could somebody please elaborate on this answer for me? I don't really feel it gives enough information for me to understand fully the "why?" part.
    Thanks
    Mark

    Hi,
    the problem is that the instace of the nested class is still existing after the execution of the method has been finished. But how should it have access to a variable which doesn't exists anymore?
    The only way to solve this problem is to declare the variable as final. Because then the value of the variable is known when the instance of the nested class is created an can be copied. Then at each place in the nested class where the variable is used, the copy is used instead. This is only valid because the value of the variable cannot be changed after the creation of the nested class' instance.
    Andre

  • 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.

  • Static nested class

    Hi there.
    Im playing around with static nested classes:
    class OuterC {
         int x = 10;
         static class Nest {
              void doStuff() {
                   System.out.println("Going");
                   //System.out.println("Should be allowed print: " + x);
                   doOtherStuff();
              public void doOtherStuff() {
                   System.out.println("Doing Stuff!");
    public class Test {
         static class OtherNest {
              void arbitraryMethod() {
                   System.out.println("Going to do arbitrary stuff...");
         public static void main(String[] args) {
              OuterC.Nest n = new OuterC.Nest();
              n.doStuff();
              OtherNest on = new OtherNest();
              on.arbitraryMethod();
    }//close TestWhen I uncomment the statement to print out the instance variable x of class OuterC
    I get a "cannot access non-static..." error, which is fine. I expect that.
    But why can I run the doOtherStuff() method from the static nested class Nest?
    doOtherStuff() is after all an instance method...
    Many Thanks & regards!
    Edited by: Boeing-737 on May 29, 2008 10:27 AM
    Dont bother replying, I see the error now. The method is defined as a member within the nested
    class. Apologies, I didn't spot that. My mistake.
    Thanks.
    Edited by: Boeing-737 on May 29, 2008 10:28 AM

    From the JLS, chapter 8:
    A nested class is any class whose declaration occurs within the body of another class or interface. A top level class is a class that is not a nested class.
    This chapter discusses the common semantics of all classes-top level (?7.6) and nested (including member classes (?8.5, ?9.5), local classes (?14.3) and anonymous classes (?15.9.5)).
    So "nested" iff "not top level".From the JLS, chapter 8:
    An inner class is a nested class that is not explicitly or implicitly declared static.
    So a "static" nested class is a bit redundant, since a "non-static" nested class -- a nested class is either static or it isn't -- is more specifically referred to as an "inner class". That's my story and I'm sticking to it. :o)
    ~

  • 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

  • Nested Class in xpress

    Could someone explain how to instantiate a nested class in xpress? Thanks

    yep sorry about the error there, but it still wont run.
    Through trial and error, ive discoverd that if I comment out the DocumentListener the jar will run fine. This is strange.
    the documentListener now looks like
    DocumentListener listener = new DocumentListener()
          public void changedUpdate(DocumentEvent documentEvent) {
          public void insertUpdate(DocumentEvent documentEvent) {
            if(proceed == true){
                   String temp = textField.getText();
                   System.out.println(temp);
                int tempo = Integer.parseInt(temp);
                   updateBet(tempo);
                   else{
          public void removeUpdate(DocumentEvent documentEvent) {
         };  with this declaration above in the code
    JTextField textField = new JTextField(4);
              final Document document = textField.getDocument();
                    document.addDocumentListener(listener);can anyone see any problems, im tearing my hair out :-<

Maybe you are looking for

  • Unable to install MS Office Proofing tools 2013 SP1 even after installing MS Office 2013

    Hi All, When I run the "proofsp1.exe" manually by double clicking on it, I get the below error message. Proofing tools has already been installed and I am trying to install Proofing tools Service Pack1.               "The expected version of the prod

  • Changing security question answers

    how do i change security question answers in i forgot them?

  • How to Get the difference between date

    Hi I try this query to find the difference between 2 date given in the below query. But the query can't be execute.. Please try this query and give the correct one... select to_date(to_char(LAST_DAY('2005/03/15')+1,'yyyy/mm/dd'),'yyyy/mm/dd') - to_da

  • Dolby 5.1 and iMac

    Has anyone found a good way to access 5.1? I was intrigued by Tritton AXPro headset which claims to have optical input and to be compatible with Mac. Has anyone tried this? and yes @ $159-$179 it is not a cheap solution,

  • Create a Menu Form

    Hi, I had create 13 Forms, but i want to create a First Form for when i "run form" appear this Form where i can choose what form i want to open, its possible?How? thank you Diana