Blatant newbie question: inner classes

I'm trying to pick up java (finally) and am working my way through the tutorial.
I am unclear as to how exactly the Class2.java program works, in the Classes and Inheritance lesson (questions page).
Specifically, when I did the exercise, I 'oopsed' and declared a variable "protected InnerClass2 ic". When I did this, my output showed that "InnerClass1: getAnotherString invoked". When I removed it, it shows "InnerClass2 version of getAnotherString invoked".
Okay... I understand that I screwed up. I'm just having some problems understanding how the scoping works resulting in my error.
If somebody could clear this up for me, I'd appreciate it.
Thanks.
John.
(The address of the page is http://java.sun.com/docs/books/tutorial/java/javaOO/QandE/nested-questions.html )

Sorry, here is the explanation:
The declaration of the variable ic in the Class2 hides the variable ic in the parent class. When you do not declare this variable in the child class the class of the ic variable in the parent class will be InnerClass2 (because of the line in the Class2 constructor ic= new InnerClass2()), and the type of this variable is InnerClass1.
Now when you invoke c2.displayStrings() in the main method of the Class2 the parent's displayStrings() method gets invoked (because there is no overriding version of this method in the child class). And in this method two other methods are invoked on the ic variable (which now has the class InnerClass2):
1 - getString() - which has no overriding version in the InnerClass2 class
and
2- getAnotherString() which is overriden in the InnerClass2 class.
So when you invoke those methods getAnotherString() in the child class will be invoked and you get the result: "InnerClass2 version of getAnother String invoked". If you try to override the other method too (getString()) you will get the result in the overriding version of the method.
This happens because the class of the variable ic (belonging to Class1) is InnerClass2 and this class has a method which overrides, and therefore hides, the method in the parent class, so the variable ic can only see the overriding version of the original method.

Similar Messages

  • Newbie question about classes

    Hi, everyone. I've created a class 'Parser' that compiles. Now I want to create and instance of this class and set/get the data members from another class. However, when I try to use it, as seen below, I get an 'javac' error. What am I doing wrong?
    public class Tester {
         static Parser my_parser = new Parser() ;
    public static void main(String[] args)
    throws Exception {
    .... other stuff
    ====== javac error =============
    bash-2.02$ javac Tester.java
    Tester.java:12: cannot resolve symbol
    symbol : class Parser
    location: class vocalreader.Tester
    static Parser my_parser = new Parser() ;
    ^
    Tester.java:12: cannot resolve symbol
    symbol : class Parser
    location: class vocalreader.Tester
    static Parser my_parser = new Parser() ;
    ^

    Here the problem is with the CLASSPATH variable. Make sure it is setted corectly (it must include the current directory ".").
    As for the static modifier, in this code static refers to the variable my_parser, of type Parser, which in this way is marked as class variable (and it belongs to class Tester). So this variable can be accessed with the following: Tester.my_parser. Why should he remove the static modifier ? It has nothing to do with the methods in the Parser class.

  • Newbie question: taskdef class org.apache.catalina.ant.DeployTask error

    Hi,
    I am trying to run one of the examples in the JWS tutorial, but everytime I go "ant build" it throws the following error
    <stuff_up_front>/jaxrpc/common/targets.xml:30: taskdef class org.apache.catalina.ant.DeployTask cannot be found
    As far as I know I have all the necessary path and environmental variable set. Only thing I can think of is that I choose not to install the Tomcat that comes bundled with the JWSDP package since I already had tomcat server running on my machine. But my Catalina_Home has been set from a long time and it works with other applications. So I really not sure what I am suppose to do. Help would be very welcomed. Thansk you.

    Please dis regard I just now noticed the dates on this thread. (I sure hope you have gotten it working by now.)
    I did get these examples running. The fact that I had several versions of Tomcat installed by IDE's I think alot of my env.vars where not pointing to the proper place. I ended up just using all the stuff that came with the jwsdp(server and likes). maybe later once I get a greater understanding I can do better. BUT I AM A BIT SLOW. Thanks all.
    If you every reply to me type slow so i can keep up.

  • Newbie question about CLASS

    I am trying to start my first flash website by using actionscript
    and I have a problem with loading image with outside actionsctipt file.
    here is the code:
    package {
        import flash.display.MovieClip;
        import flash.display.Loader;
        import flash.net.URLRequest;
        public class Index_page extends MovieClip {
            private var req:URLRequest=new URLRequest("picture/index_page/image_logo.png");
            private var logoLoader:Loader = new Loader();
            logoLoader.load(req);
            addChild(logoLoader);
    when I publish the swf file, it comes out the error message saying,
    access to undefined property logoLoader as well as req and logoLoader.
    and the method addChild also became undefined.
    How could that be since I`ve already declared those variables at the beginning?
    But, if I put them in a function like this, it works.
    public function Index_page() {
                logoLoader.load(req);
                addChild(logoLoader);
    my point is,
    Does it neccessary to make so many lines for only loading an image?
    or there is a better way to do this. I am not really famiier with package
    and class things...thanks for any help!

    Code within a class must be within a method, or in the constructor. The example you gave:
    public class Index_page extends MovieClip {
            private var req:URLRequest=new URLRequest("picture/index_page/image_logo.png");
            private var logoLoader:Loader = new Loader();
            logoLoader.load(req);
            addChild(logoLoader);
    as code outside of any method... you can't do that. In your second example you placed it in the constructor - the method that is automatically run when the class is instantiated - the method that has the same name as the class. Only variable declarations can go outside a method definition...

  • Newbie question: custom classes

    So I decided to learn Java. I have been going strong for the past 3 days, building a web crawler (I learn by doing).
    So far, I love it. I am a good halfway through writing it and i have not gotten stumped till now. I was happily coding away at my main class, when I realized I needed to make a new class.
    When I put a public class in the same file with the main class, the compiler complains about it being public.
    When it is a private class, I can't use it in my main class.
    When I make it a public class and put it in a separate file, the compiler can't find it.
    I have searched and searched but what little I can find is ambiguous, making references to strange, unfamiliar constructs.
    I miss #import "class.h".

    The main class is real long but heres it basically:
    public class Crawler {
         public static StringBin crawled = new StringBin(3);
         public static String domain = "";
         public static void main(String[] args) {
              crawl("http://www.google.com/");
              crawl("http://www.google.com/ig");
         public static int crawl(String location) {
         Socket socket = null;
         try {
              String currentURL = location;
              //Check/Set uniqueness
              if (crawled.contains(currentURL)) {
                   return 0;
              } else {
                   crawled.add(currentURL);
              return 1;
              } catch (Exception e) {
                   System.err.println(e);
                   return 0;
              } finally {
                   if (socket != null) {
                        try { socket.close(); }
                        catch (Exception e) { System.err.println(e); }
    }And here is the StringBin class:
    public class StringBin {
         private static String[] array;
         private static int size=0;
         private static int increment;
         public static void StringBin(int n) {
              increment = n;
              array = new String[n];
         public static void add(String str) {
              if (size == array.length) {
                   String[] newarray = new String[array.length+increment];
                   System.arraycopy(array, 0, newarray, 0, array.length);
                   array = newarray;
              size++;
              array[size] = str;
              Arrays.sort(array);
         public static Boolean contains(String str) {
              int i=Arrays.binarySearch(array, str);
              if (i < 0) return false;
              return true;
    }The purpose of stringbin was to get a relatively efficient way of storing a group of strings and searching within them. I don't even know if it works.
    They are in the same folder.
    Message was edited by:
    111cix

  • Design question about when to use inner classes for models

    This is a general design question about when to use inner classes or separate classes when dealing with table models and such. Typically I'd want to have everything related to a table within one classes, but looking at some tutorials that teach how to add a button to a table I'm finding that you have to implement quite a sophisticated tablemodel which, if nothing else, is somewhat unweildy to put as an inner class.
    The tutorial I'm following in particular is this one:
    http://www.devx.com/getHelpOn/10MinuteSolution/20425
    I was just wondering if somebody can give me their personal opinion as to when they would place that abstracttablemodel into a separate class and when they would just have it as an inner class. I guess re-usability is one consideration, but just wanted to get some good design suggestions.

    It's funny that you mention that because I was comparing how the example I linked to above creates a usable button in the table and how you implemented it in another thread where you used a ButtonColumn object. I was trying to compare both implementations, but being a newbie at this, they seemed entirely different from each other. The way I understand it with the example above is that it creates a TableRenderer which should be able to render any component object, then it sets the defaultRenderer to the default and JButton.Class' renderer to that custom renderer. I don't totally understand your design in the thread
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=680674
    quite yet, but it's implemented in quite a bit different way. Like I was saying the buttonClass that you created seem to be creating an object of which function I don't quite see. It looks more like a method, but I'm still trying to see how you did it, since it obviously worked.
    Man adding a button to a table is much more difficult than I imagined.
    Message was edited by:
    deadseasquirrels

  • Inner Class Question

    My question pertains to the code at the bottom of this post.
    I don't understand why the compiler doesn't give an error for the line below. Why would it let you refer to something inside the class (in this case I'm referring to ClassWithInnerClass.MyInnerClass) unless it were static?
    ClassWithInnerClass.MyInnerClass mic = cwic.retMyInnerClass();To illustrate why I'm asking, I created 2 ints ("regularInt" and "staticInt") inside class "ClassWithInnerClass". The compiler let me set the value of "staticInt" from within main whereas it wouldn't let me do so w/ "regularInt" (which is why I commented that line out). Don't get me wrong though - I understand the reasons why the compiler behaves as it does for "regularInt" and "staticInt". I understand that a static variable can be accessed without instantiating a class (and that there's only 1 created no matter how many classes are instantiated). I also understand that, to access a non-static variable, you need to instantiate a class. My question arises only because of trying to extend that logic to MyInnerClass.
    I can already take a guess that the answer is going to be something like, "the reason it works this way is because class 'MyInnerClass' is just a declaration NOT a definiton". I guess I just want confirmation of this and, if possible, some reasoning behind this logic.
    HERE'S THE CODE...
    class CreateInnerClasses {
         public static void main (String args[]) {
              ClassWithInnerClass cwic = new ClassWithInnerClass();
              ClassWithInnerClass.MyInnerClass mic = cwic.retMyInnerClass();
              //ClassWithInnerClass.regularInt = 5;
              ClassWithInnerClass.staticInt = 10;
              mic.printIt();
    class ClassWithInnerClass {
         public int regularInt ;
         static public int staticInt;
         class MyInnerClass {
              void printIt() {
                   System.out.println("Inside ClassWithInnerClass.myInnerClass");
         MyInnerClass retMyInnerClass () {
              return new MyInnerClass();

    The line    ClassWithInnerClass.MyInnerClass mic = cwic.retMyInnerClass();is accepted because the name of the inner class is ClassWithInnerClass.MyInnerClass. This has nothing to do with accessing fields even though the syntax is similar.
    On the other hand, the line    SomeClassWithAnInnerClass.InnerClass ic = new SomeClassWithAnInnerClass.InnerClass();is not accepted because the nested class SomeClassWithAnInnerClass.InnerClass is not static: you must have an instance of the outer class available. The correct syntax for calling the constructor of the inner class would be    Outer.Inner instance = outerInstance.new Inner();In this case you could write:    ClassWithInnerClass.MyInnerClass mic =  new SomeClassWithAnInnerClass() . new InnerClass();
        // OR:
        ClassWithInnerClass.MyInnerClass mic =  cwic . new InnerClass();The Java tutorial has a pretty good explanation on nested classes:
    http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html
    http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html

  • Inner classes question

    Hi guys,
    I have a question to ask - when i'm writing an inner class and i want to create a new instance from it, the Eclipse forces me to use an instance of the containing class to call new.
    Is it how it's done or am i doing something wrong?
    public class A
        // Some code here
        public class B
             //Some code here
    }Trying to create an instance:
    A a = new A();
    A.B b = a.new B();

    What you have defined is "non-static" inner class.A "non-static" can only be instantiated only if we create an object of outer class.True.
    >
    There are two ways to create "inner" class object,
    1)The way you have written the codeTrue.
    2)
        public class A
    {    // Some code here    
    public void createInner()
    classB b=new ClassB();
    public classB   
    //Some code here   
    That code won't compile. Even if you corrected it so that it did compile, it doesn't really help in the OP's situation. Did you read the advice of Saish and Jos about why class 'B' probably shouldn't be public, anyway?

  • Design question on inner class

    I have an app, with a JPanel. The way I have it setup right now is the JPanel is an inner class with an overloaded constructor. I call the inner class depending on the arguements. this is done repeatedly in my program.
    My question is: Should I be doing it this way or maybe as a method that returns the updated JPanel? Can this cause serious memory problems?
    example
    private void CreateTextfields(int q, int c){
    // c =      number of choices selected from other JComboBox
    // q =      question selected from combo box
    // questions is the arrylist containing all questions
       AnswerPanel answerPanel;
       answerPanel = null;
       textFieldPanel.removeAll();
    if( questions.isEmpty() && c > 0 ){
             answerPanel = new AnswerPanel(c);
    else if( !questions.isEmpty() && c == 0 ){
             answerPanel = new AnswerPanel(q, listOfAnswers);
    else if( !questions.isEmpty() && c > 0 ){
             clearLogic();
             answerPanel = new AnswerPanel(q, listOfAnswers, c);
             textFieldPanel.add( answerPanel, BorderLayout.CENTER ); Thanks
    Jim

    <<serious memory problems>>
    Probably not. But it seems wasteful to keep creating a new object just to set some properties. Why not make a single AnswerPanel, with overloaded setContents() functions?
    Not that I'm a Swing expert or anything....
    HTH,
    Ken

  • Question on inner classes

    I have a class that has 3 inner classes, on class read the colors and font settings, how can I pass this class to the 2 other inner classes
    Here is a watered down version of code:
    class MainClass{
           public MainClass(){
                 // do some stuff
                 innerClass3  ic = new innerClass3();// I need to pass this to the other inner classes
                 layeredPane.add( new innerClass1( some Variable), 1);
                 layeredPane.add( new innerClass2( anotherVariable), 2 );
    class innerClass1 extends JTextPane{
         public innerClass1( String s ){
    // instead of doing this
              innerClass3 ic = new innerClass3();
              setBackground(ic.getBackground() );
    class innerClass2 extends JPanel{
            public innerClass2( String[] z){
             // and this again
                innerClass3 ic = new innerClass3();
                setForeground(ic.getFontClor());
    class innerClass3{
    Color background;
    Color foreground;
        public innerClass(){
         setColors();
    public void setColors(){
       background = Color.blue;
       foreground = Color.red;
    public Color getBackground(){
       return background;
    public Color getFontColor(){
    return foreground;
          

    Thanks for the reply
    Works well for first screen, but I recall the innerClasses(1 and 2) from an actionPerformed in innerClass2 and I keep getting nullPointerError when referring to innerClass3. Each screen will have different fonts and colors, so I need it to update after each button click.
    // this is inside innerClass2( it's panel with buttons )
    // the next screens graphics will depend on which button is selected
    public void mouseReleased(final java.awt.event.MouseEvent e) {
             layeredPane.removeAll();
              currentQuestionNumber++; 
              question = questionText[currentQuestionNumber] ;  
    // adds a JTextPane with question         
              layeredPane.add(new innerClass1(question, ic), 1 );
    // adds a JPanel with buttons
              layeredPane.add(new innerClass2( currentQuestionNumber, ic ), 3 );Will be tearing hair out soon
    Jim

  • A question about non-static inner class...

    hello everybody. i have a question about the non-static inner class. following is a block of codes:
    i can declare and have a handle of a non-static inner class, like this : Inner0.HaveValue hv = inn.getHandle( 100 );
    but why cannot i create an object of that non-static inner class by calling its constructor? like this : Inner0.HaveValue hv = Inner0.HaveValue( 100 );
    is it true that "you can never CREATE an object of a non-static inner class( an object of Inner0.HaveValue ) without an object of the outer class( an object of Inner0 )"??
    does the object "hv" in this program belong to the object of its outer class( that is : "inn" )? if "inn" is destroyed by the gc, can "hv" continue to exist?
    thanks a lot. I am a foreigner and my english is not very pure. I hope that i have expressed my idea clearly.
    // -------------- the codes -------------------
    import java.util.*;
    public class Inner0 {
    // definition of an inner class HaveValue...
    private class HaveValue {
    private int itsVal;
    public int getValue() {
    return itsVal;
    public HaveValue( int i ) {
    itsVal = i;
    // create an object of the inner class by calling this function ...
    public HaveValue getHandle( int i ) {
    return new HaveValue( i );
    public static void main( String[] args ) {
    Inner0 inn = new Inner0();
    Inner0.HaveValue hv = inn.getHandle( 100 );
    System.out.println( "i can create an inner class object." );
    System.out.println( "i can also get its value : " + hv.getValue() );
    return;
    // -------------- end of the codes --------------

    when you want to create an object of a non-static inner class, you have to have a reference of the enclosing class.
    You can create an instance of the inner class as:
    outer.inner oi = new outer().new inner();

  • Question about inner class - help please

    hi all
    i have a question about the inner class. i need to create some kind of object inside a process class. the reason for the creation of object is because i need to get some values from database and store them in an array:
    name, value, indexNum, flag
    i need to create an array of objects to hold those values and do some process in the process class. the object is only for the process class that contains it. i am not really certain how to create this inner class. i tried it with the following:
    public class process{
    class MyObject{}
    List l = new ArrayList();
    l.add(new MyObject(....));
    or should i create the object as static? what is the benifit of creating this way or static way? thanks for you help.

    for this case, i do need to create a new instance of
    this MyObject each time the process is running with a
    new message - xml. but i will be dealing with the case
    where i will need a static object to hold some
    property values for all the instances. so i suppose i
    will be using static inner class for that case.The two situations are not the same. You know the difference between instance variables and static variables, of course (although you make the usual sloppy error and call them static objects). But the meaning of "static" in the definition of an inner class is this: if you don't declare an inner class static, then an instance of that inner class must belong to an instance of its containing class. If you do declare the inner class static, then an instance of the inner class can exist on its own without any corresponding instance of the containing class. Obviously this has nothing to do with the meaning of "static" with respect to variables.

  • Inner classes - a general question

    i'm having some difficulties understanding when to use a static inner class
    and when to use a non static inner class
    lets say i'm implementing a LinkedList , and i want my nodes and my iterator
    implemented in inner classes .
    when and why should i declare them static or non static.
    thank you very much in advance.

    Inner classes are never static. Nested classes can be either static or non-static; a non-static nested class is called an inner class.
    Anyway, an inner class implicitly gets a reference to an object of the outer class, while a static nested class doesn't, so the decision should depend on whether or not it needs that.
    An iterator would need a reference to its collection so it would be a non-static nested class. A node wouldn't so it would be a static nested class.

  • A question about local inner classes

    Suppose an inner class created in a method:
    public void thisMethod(final int a){
                 class InnerClass {
                   //code
    }Why, in order to use the parameter a in the inner class, I have to pass it final?

    Aurelious wrote:
    JoachimSauer wrote:
    Because you can't refer to the argument of a method once the method call is completed (since the method argument lives on the stack).Why does that matter? If the parameter is of a primitive type, the object will get a copy of it anyway. If the parameter is not primitive, then the value on the stack will be a reference to the argument and not the argument-object itself. In either case, it should then be safe to modify the value after the method returns, as it will either be the primitive copy or a copy of a reference to the object which is itself not on the stack, so the field referenced by the object is still valid either way.
    Am I missing something?If your inner class is using a local variable in the calling method, the expectation is that it's the same variable. But it's not. If it were, then when the stack frame was popped, the variable would be out of scope, which is incompatible with the fact that the inner object can live on.
    On the other hand, if we copy it without making it final, then that's misleading. It looks like I have the same variable, but if I change it in the method, it doesn't change in the object, and vice versa.
    So we have to make a copy to prevent scope/lifetime problems, and we have to make it final so that the copy can be indistinguishable from it being the same variable.

  • Question about anonymous inner class??

    Is there any error occurs,If a class declear & implement two anonymous inner classes ??

    public class TryItAndSee {
        void m() {
            Runnable x = new Runnable(){
                public void run() {
                    System.out.println("?");
            Runnable y = new Runnable(){
                public void run() {
                    System.out.println("!");
    }

Maybe you are looking for

  • My time capsule is definetly slow

    Hello all! I just bought a 1TB time, very nice item, but I'm really upset for its performances, it's really too slow. I warmly hope it's cause my configurations otherwise I've to return it to apple so I hope I can get some good suggestion from you sk

  • GL is Empty in Service PR

    Hi, We're creating a PR with account assignment F & Item Category D and material Group X (no material master is used) from CRM. In ME52N, i dont see a GL account assignment GL is supposed to be retrieved automatically ("account assignment" tab) from

  • Transfer from iPad to MacBook Air

    I'd like to transfer some songs from my iPad to my MacBook Air.  I understand this is possible but when I follow the steps I don't see a choice to transfer SELECTED items - only ALL the items I've purchases on my iPad will transfer.  Is there a way t

  • Is it possible to manage multiple investments from one bank in one g/l acct

    HI, My client has multiple investments in different plans with the same bank. eg: KOTAK LIQUID (INSTITUTIONS) - DAILY DIVIDEND KOTAK FLOATER LONG TERM - DAILY DIVIDEND Is it possible to manage both of these in one G/l account. Thanks and Regards, Sai

  • Problems with PC Suite and bluetooth connection to...

    Hi, I have the following: Pentium 4 PC running Windows XP service pack 2 PC Suite 6.82.22.0 PC Connectivity Solution: Version 6.43.9.0 Bluetooth stack: Microsoft Bluetooth stack Version 5.1.2600 Build 2180 I have had repeated problems trying to get a