Page 1 of 2 12 LastLast
Results 1 to 20 of 36
  1. #1
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Struggling with inner classes

    Find here two small programs that contain inner classes.
    What is actually the difference between Inner Classes and Static Inner Classes?
    Do Static Inner Classes make any sense?
    So yes, which?


    Java Code:
    public class OuterClass
    {
    *** private int private_member_variable = 100;
    *** public class InnerClass
    *** {
    ******* public void printPrivateVariable()
    ******* {
    *********** System.out.println(private_member_variable);
    ******* }
    *** }
    *** public void callInnerClassMethod()
    *** {
    ******* InnerClass innerClass = new InnerClass();
    ******* innerClass.printPrivateVariable();
    *** }
    *** public static void main(String args[])
    *** {
    ******* OuterClass outerClass = new OuterClass();
    ******* outerClass.callInnerClassMethod();
    *** }
    }

    =====================================


    Java Code:
    public class OuterClass
    {
    *** private int private_member_variable = 100;
    
    *** public static class StaticInnerClass
    *** {
    ******* public void printPrivateVariables()
    ******* {
    *********** OuterClass outerClass = new OuterClass();
    *********** System.out.println(outerClass.private_member_variable);
    ******* }
    *** }
    
    *** public static void main(String args[])
    *** {
    ******* StaticInnerClass staticInnerClass = new StaticInnerClass();
    ******* staticInnerClass.printPrivateVariables();
    *** }
    }
    
    
    public class Test
    {
    *** public static void main(String args[])
    *** {
    ******* OuterClass.StaticInnerClass staticInnerClass = new OuterClass.StaticInnerClass();
    ******* staticInnerClass.printPrivateVariables();
    *** }
    }

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    4,041
    Rep Power
    10

    Default Re: Struggling with inner classes

    I'm not really sure what your question is. Static inner classes work exactly how static anything else works: you don't need an instance of the containing class to use them. non-static inner classes require an instance of their containing class.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,036
    Rep Power
    6

    Default Re: Struggling with inner classes

    Think of nested classes as a small package which serves the containing class. A typical use of a non-static member class would be to implement an iterator for some type of collection. Since the iterator needs access to the collection a non-static class is appropriate. A typical use of a static inner class would be to package some information that might be used by the enclosing class but does not need access to the enclosing class itself. A basic rule of thumb for determining if the inner class should be static or not. If the class could be used as top level public class (i.e. does not require an instance of its enclosing class) then make it static. There is less overhead (in terms of enclosing class references that will never be used).

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  4. #4
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: Struggling with inner classes

    Jim
    Since the class is declared static, why instead of saying "staticInnerClass.printPrivateVariables();"
    through an created object of the class,
    you can not say just StaticInnerClass.printPrivateVariables(); without creating an object first?

  5. #5
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,036
    Rep Power
    6

    Default Re: Struggling with inner classes

    Because a static inner class is no different than a regular top level class. The term static only describes its relationship to its enclosing class. Not how it accesses its methods. To use a static inner class you must still create an instance of it. But to do so you do not need an instance of the enclosing class. If the static inner class methods are declared static then you can do what you said. If they are not declared static then you need an instance of the inner class to access them. In summary, a static inner class may have instance fields and static fields and instance methods and static methods, just like a regular top level class. Here is an example of using static inner classes. Notice that as long as the inner class is public and visible, I don't need to even mention the enclosing class to instantiate it.

    Java Code:
    public class TestStaticClasses {
    
       public int v = 10;
       public static void main(String args[]) {
           TopLevel2.FooBar foo = new TopLevel2.Foobar(); // fixed - JosAH
           foo.printv();
           TopLevel2.Foobar.cool(); // fixed - JosAH
           TopLevel2.Foobar foo2 = new TopLevel2.Foobar();
           foo2.printv();
           TopLevel2.Foobar.cool();
       }
       
    }
    
    class TopLevel2 {
       public static class Foobar {
          int s = 10;
          public void printv() {
             TestStaticClasses r = new TestStaticClasses();
             System.out.println(r.v);
             System.out.println(s);
             System.out.println(this.s);
          }
          public static void cool() {
             System.out.println("This is static");
          }
       }
       
    }
    This code prints out the following:

    10
    10
    This is static
    10
    10
    This is static


    Jim
    Last edited by JosAH; 02-22-2013 at 08:15 PM. Reason: Jim asked me to fix the code a bit
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  6. #6
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: Struggling with inner classes

    The strange fact is that when a class containing a static fields or static methods is instanced into several object, there will always be just one copy of that static field and static method. So making an instance of a class does not influence static fields and methods, right.
    Making an instance of a class has little to do with static fields or static methods!
    A static class, in general makes no sense, right?
    But a static inner class does, and one should even makes an instance of it to use it (actually not of the outer class which contains the inner class). All his is not what one calls obvious?

  7. #7
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: Struggling with inner classes

    Futher studying this weird subject I found this example and like to ask if the example is real?
    And why I can not get to cook?

    Java Code:
    interface Cookable {
         public void cook();
    }
    class Food {
        Cookable c = new Cookable() {// looks like you are instantiated a interface (not possible) 
        public void cook() {
        System.out.println("anonymous Cookable implementer");
        }
        
        
       };
       public static void main(String args[]) {
            Food fd = new Food();
            fd.cook(); // can not get to cook
       }
    }

  8. #8
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: Struggling with inner classes

    BTW thanks jim for that example I'll study it!

  9. #9
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: Struggling with inner classes

    The output of yours, jim looks weird, do not know what System.out.println(this.s); would print
    so have to pull it through the compiler to see what happens...

  10. #10
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: Struggling with inner classes

    What am I doing wrong? Getting an error message! Have the the classes TestStaticClasses and TopLevel2 in two different files (same package)

    Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - cannot find symbol
    symbol: class Foobar
    location: class willemlearningjava.TestStaticClasses
    at willemlearningjava.TestStaticClasses.main(TestStat icClasses.java:16)
    Java Result: 1
    BUILD SUCCESSFUL (total time: 2 seconds)

  11. #11
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,036
    Rep Power
    6

    Default Re: Struggling with inner classes

    First, you may instantiate an interface if it is done anonymously and all methods are implemented (they may be empty but need to return appropriate types). What you are doing in reality is instantiating an anonymous class that is implementing only the interface methods.

    Second, class Food did not implement the interface. Yet you are trying to access cook via an instance of Food.

    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  12. #12
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,036
    Rep Power
    6

    Default Re: Struggling with inner classes

    My code is in the same file. TopLevel2 is a non-public class in the same package. If you put it in a different file then you need to make it public and the file must be named TopLevel2.java.

    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  13. #13
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,036
    Rep Power
    6

    Default Re: Struggling with inner classes

    Yes. There is no such thing as a static top level class. Only inner classes may be declared static.

    Consider the java.lang.Math class. It contains nothing but static methods that act on parameters that have nothing to do with an instance of Math. In fact, you can't instantiate Math at all. It is declared final and has a private constructor. Its declaration starts out as:

    Java Code:
    public final class Math {
    
        /**
         * Don't let anyone instantiate this class.
         */
        private Math() {}
        ...
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  14. #14
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: Struggling with inner classes

    Jim the code is not compiling. Have the two classes together in the file named:
    TestStaticClasses
    like you said,
    here is your code as I put it together:

    Java Code:
    package willemlearningjava;
    
    /**
     *
     * @author willem
     */
    class TopLevel2 {
       public static class Foobar {
          int s = 10;
          public void printv() {
             TestStaticClasses r = new TestStaticClasses();
             System.out.println(r.v);
             System.out.println(s);
             System.out.println(this.s);
          }
          public static void cool() {
             System.out.println("This is static");
          }
       }
    
    }
    
    public class TestStaticClasses {
    
       public int v = 10;
       public static void main(String args[]) {
           Foobar foo = new Foobar();
           foo.printv();
           Foobar.cool();
           TopLevel2.Foobar foo2 = new TopLevel2.Foobar();
           foo2.printv();
           TopLevel2.Foobar.cool();
       }
    
    }
    Last edited by willemjav; 02-22-2013 at 07:17 PM.

  15. #15
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: Struggling with inner classes

    The class which contains the main method should always be public right?

  16. #16
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: Struggling with inner classes

    Here I found a good explanation of inner classes:

    Java - Inner Classes

  17. #17
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,785
    Blog Entries
    7
    Rep Power
    21

    Default Re: Struggling with inner classes

    From the outside, the name of that static nested class isn't FooBar, it is TopLevel2.Foobar, so the first line of your main( ... ) method isn't correct.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  18. #18
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: Struggling with inner classes

    Ya, like wooden russian dolls great jos thanks

    so here are the correct lines

    TopLevel2.Foobar.cool();
    TopLevel2.Foobar foo2 = new TopLevel2.Foobar();
    foo2.printv();
    TopLevel2.Foobar.cool();
    Last edited by willemjav; 02-22-2013 at 07:27 PM.

  19. #19
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,036
    Rep Power
    6

    Default Re: Struggling with inner classes

    That was my mistake. My IDE did an automatic import of that class.

    import yourpackage.TopLevel2.Foobar;

    I should have caught it.

    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  20. #20
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    9

    Default Re: Struggling with inner classes

    No problem jim, now I can start looking what happens when the app. runs
    thanks booth jos and jim

Page 1 of 2 12 LastLast

Similar Threads

  1. Struggling need help
    By acbar in forum New To Java
    Replies: 2
    Last Post: 07-16-2012, 06:00 AM
  2. Struggling with overriding abstract classes
    By Stubkan in forum New To Java
    Replies: 3
    Last Post: 03-12-2012, 11:07 AM
  3. Struggling to import JAR
    By Mr ChriZ in forum Android
    Replies: 0
    Last Post: 01-12-2012, 11:53 AM
  4. Struggling with this code
    By Shimless12 in forum New To Java
    Replies: 5
    Last Post: 07-14-2011, 07:06 PM
  5. Struggling with AlphaComposite .. please help me
    By jeshmal4u in forum Java 2D
    Replies: 3
    Last Post: 03-08-2010, 06:11 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •