Inner/Outer classes - curious matter

Hi,
This is from Sun Certified Programmer practice exam:
class Outer {
   class Inner {}
class ExtendedOuter extends Outer {
   class ExtendedInner extends Inner {}
class Main extends Outer.Inner {
   Main( Outer ref ) {
        ref.super();
   public static void main( String[] args ) {
        new Main( new ExtendedOuter() );
}The choices are:
A) Compilation fails
B) An exception is thrown at runtime
C) The code runs with no output
My answer was A because the line ref.super() doesn't make sense to me.
But the correct answer is C.
As far I as knew - super is a keyword and can be used either to access hidden members of the superclass, or to invoke specific constructor from the superclass also. What is it here???
Could somebody explain what this line does?

Is that because class files with no declared package
location are automatically placed in the same
package?Classes with no declared package are all part of an unnamed package, commonly referred to as the default package.
In general, you should always use packages, as support for unnamed packages is implementation dependent (although all compilers and JVMs must support an unnamed package). Depending on the platform you are using, the unnamed package might include all directories and jar files on your classpath, just the current working directory, just the first directory on your classpath, or something else.
But `ref' is not an instance of Main, but is an
instance of ExtendedOuter (whose superclass is
Object). Actually ExtendedOuter's superclass is Outer. However all that is important is that it is an instance of Outer, since the type checking is performed at compile time.
So how can it be calling Main's?Because it is a superclass constructor invocation in class Main. Therefore it calls a constructor in Main's superclass. This is the syntax used to call a superclass constructor where the superclass is an inner class and the enclosing instance needs to be specified. ref is the object to be used as the enclosing instance - there is no clever trick to it - it is just a syntax.
Also, if an instance of an innerclass exists, than an
instance of it's outerclass must also exist. Yes, in the example the outer class instance is ref.
Then
won't calling the constructor of a superclass (with
`ref.super()') be calling the constructor again after
it (the superclass) has already existed?You can not create an object (other than instances of java.lang.Object) without calling a superclass constructor.

Similar Messages

  • Question about Inner/Outer classes

    Hello!
    I'm still preparing for java cert exam and have a question. If I have Outer and Inner classes like this:
    Outer o = new Outer();
    Outer.Inner i = o.new Inner();Does this mean that 'i' has a reference to both Outer and Inner classes. Moreover, does 'i' have a reference to the 'this' of 'o'?
    Thanks,
    Victor.

    "i" doesn't have a reference. "i" is a reference. I think you are trying to express this:
    import java.lang.reflect.*;
    public class Outer {
        class Inner {
            private int foo;
        public static void main(String[] args) {
            Outer o = new Outer();
            Outer.Inner i = o.new Inner();
            for(Field field : i.getClass().getDeclaredFields()) {
                System.out.format("%s %s %s;%n", Modifier.toString(field.getModifiers()),
                    ((Class)field.getGenericType()).getName(), field.getName());
    }

  • Getting the name of outer class in an inner class

    Hi,
    I have a private inner class, something like this:
    public class OuterClass extends AnotherClass {
    public OuterClass() {
    supre();
    private class innerClass1 extends SomeotherClass {
    protected void someMethod() {
    // how to get the name of outer class, that is, "OuterClass"
    Can someone please tell me how to get the name of the outer class inside the inner class method?
    Thanks in advance..
    Prasanna

    getClass().getEnclosingClass().getName()But then, you already know it, don't you?

  • Hw To Make Inner Class Distinguish Func Parameter And Outer Class Var

    i fail to make an inner class distinguish among function parameter and outer class variable.
    consider the following code:
    public class a {
         int var; // i want to access this one using inner class.
         public a(int var) {
              this.var = var;
              class b {
                   public void fun() {
                        var = 100;
    i get an error a.java:9: local variable var is accessed from within inner class; needs to be declared final.
    when i change the code to this:
    public class a {
         int var; // i want to access this one using inner class.
         public a() {          
              class b {
                   public void fun() {
                        var = 100;
    it compiled no problem.it seems that inner class is accessing function parameter rather than outer class member.
    is there any syntax i can use to make me access the outer class member variable whithout renaming or removing the function parameter?
    thank you.

    a.this.var = 100; //Use this in the inner class.Amazing syntax -:)

  • Outer Class Accessing Inner Classes Variables

    Hi Everyone,
    Should an outer class directly access the private member variables of its inner class? Or should it get their values by calling an appropriate 'getXXX()' method?
    Just wondering.
    Thx.

    If the outer class trys to access the variable that is declared in the inner class with in a class and outside the method, then it can access in the following example
    class outer
         private int x=10;
         class inner
              int y=20;
         public void getOutput()
              inner in=new inner();
              System.out.println("The value of y is" +in.y);
         public static void main(String args[])
              outer out=new outer();
              out.getOutput();
    };

  • Inner class access to outer class variables

    class X extends JTextField {
    int variable_a;
    public X() {
    setDocument(
    new PlainDocument() {
    //here i need access to variable_a
    i don't want to make variable_a a static member though, so does anyone know how to do it?

    Generally, you can reference your variable_a just as you would any other variable except if your inner class also defines a variable_a. However, to produce a reference to the enclosing outer class object you write "OuterClassName.this". So, to get to your variable I think you would write "X.this.variable_a". I hope this helps.

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

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

  • Accessing outer class memebers (objects) from inside a local class

    Why is it neccessary that any Member-Object reference of the Outer class, or rather even the Object references defined inside the method, which contains the local/anonymous class, has to be declared as "final" if the reference is tobe used inside the definition of the inner class??

    This feature of Java has often annoyed me. The Java Tutorial simply says "A nested class declared within a method or other smaller block of code has access to any final, local variables in scope", without explanation.
    I can think of a partial explanation: if inner classes could access non-final variables, this code would compile:
    void aMethod()
    int x = 5;
    // button is a member variable of this class
    button.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    x = 6;
    but actionPerformed may be called long after aMethod returns and x ceases to exist, resulting in an exception.
    However, requiring that x be final doesn't solve all problems. You wouldn't be able to write x = 6 if x was final, but you would be able to write System.out.println(x), which is equally problematic.

  • Getting my hands on var/methods of outer classes

    Hello,
    I am learning java these days (at school) and i ran into a problem having an action listener as a inner class, how do i get access to methods and variables of the outer class from the inner class ??
    for instance, this is my Outer class's constructor:
         public GBLEditor() {
              super("GridBagLayout Editor");
              ToolBar toolBar = new ToolBar();
              setJMenuBar(new MainMenuBar());
              getContentPane().add(toolBar, "North");
              Table tbl = new Table();
              getContentPane().add(new JScrollPane(tbl), "Center");
              getContentPane().add(new StatusPanel(), "South");
              MenuToolBarActionListener actionListener = new MenuToolBarActionListener();
              toolBar.getNewButton().addActionListener(actionListener);
              toolBar.getOpenButton().addActionListener(actionListener);
              toolBar.getSaveButton().addActionListener(actionListener);
              toolBar.getGenerateButton().addActionListener(actionListener);
              toolBar.getNewRowButton().addActionListener(actionListener);
              toolBar.getUpRowButton().addActionListener(actionListener);
              toolBar.getDownRowButton().addActionListener(actionListener);
              toolBar.getHelpButton().addActionListener(actionListener);
              setSize(770,300);
              setVisible(true);
    So if the button newRowButton is pressed in my toolbar, i need to access the tbl object's method getTableModel() from inside the inner class below (as far as i can see now)
    And this is my inner class:
    class MenuToolBarActionListener implements ActionListener {
              public void actionPerformed(ActionEvent e) {
    any ideas?

    Now your toolBar is local constructor's variable.
    Just declare it outside the constructor and you'll have access to it from methods of inner class.
    Something like this:
    public class GBLEditor extends ... {
        private Table tbl;
        public GBLEditor() {
            tbl = new Table();
        class MenuToolBarActionListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
               tbl.getTableModel();
    }

  • Reference outer class explicitly

    Hi, I have this code:
    public class Outer {
      public class Inner {
        public String getName() {
          return "inner";
        public String getOuterName() {
          return ""; // ????????????????????????
      public String getName() {
        return "outer";
    }Where I have the question marks I want to know how to explicitly call the getName method for the enclosing class of the Inner class instance. What I've always done is make a new method in Outer called "doGetName" and then I can reference it from the inner class since the inner class doesn't have a method by the same name. But that solution is clumsy. I know that all inner classes have references to their outer class...
    Anyway, any help would be much appreciated!

    try
    return Outer.this.getName();

  • Hey,i forgot my login password,so i changed the password by using terminal command(reset password).now i have new user name with new password,but i can't find  my data which i have saved on mac.please help me out in this matter.

    hey,i forgot my login password,so i changed the password by using terminal command(reset password).now i have new user name with new password,
    but i can't find  my data which i have saved on mac.the storage is showing data used and free space on the disk
    please help me out in this matter.

    How did you change your user name?
    resetpassword wouldn't have done it. If you managed to create a new user, then your data is still in the old account.

  • I have been trying for three days to try and get this working , and tried a few of the forum suggestions already and this is just to try them ... so glad i haven't pais anything yet . i get the signed out loop no matter what i try

    i have been trying for three days to try and get this working , and tried a few of the forum suggestions already and this is just to try them ... so glad i haven't pais anything yet . i get the signed out loop no matter what i try

    What have you been trying for three days to try and get this working???
    Supply pertinent information for quicker answers
    The more information you supply about your situation, the better equipped other community members will be to answer. Consider including the following in your question:
    Adobe product and version number
    Operating system and version number
    The full text of any error message(s)
    What you were doing when the problem occurred
    Screenshots of the problem
    Computer hardware, such as CPU; GPU; amount of RAM; etc.

  • Inner / outer table in nested loops join

    I can't understand what 'inner' / 'outer'
    table means in nested loops join operation.
    please explain the exact meaning.
    maybe i do not understand the nested loops
    join itself. I tried to find the meanings
    in Oracle manual, but I couldn't.

    If I understand correctly your question. An outer table loop is where you have a table with a primary key (master table) and you want to iterate into that table which have details forign key (inner loop table) for example you have customers table each have many invoices.
    hope that ansowers your query.
    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by 4baf:
    I can't understand what 'inner' / 'outer'
    table means in nested loops join operation.
    please explain the exact meaning.
    maybe i do not understand the nested loops
    join itself. I tried to find the meanings
    in Oracle manual, but I couldn't.<HR></BLOCKQUOTE>
    null

  • 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();
    }

Maybe you are looking for