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

Similar Messages

  • When  we going to use static inner class

    Hi
    when we r going use static inner class
    inner classes use for to create adaptorclasses that implement an interface.
    what about Static inner class
    if possible give some examples
    Thanks in adv

    static inner classes are used when the inner class does not require to access the encompassing class's variables/methods. By default non-static inner classes obtain a reference to the outer class instance through which they access the outer class variables and methods
    ram.

  • Why a non static member class can be defined in an interface

    Non-static member classes are defined as instance members of other classes, just like fields and instance methods are defined in a class. An instance of a non-static member class always has an enclosing instance associated with it.
    An interface can't be instantiated then how a non static member class will have an enclosing instance associated with it.
    interface outer
            public  class inner{
            public void p()
                System.out.println("inside interface's non static member class");
        public  static class inner1{
                public void p(){System.out.println("inside interface's  static member class");
    public class Client {                                           // (11)
        public static void main(String[] args) {                    // (12)
        outer.inner nonStatic = new outer.inner();
            nonStatic.p();
        outer.inner1 stat = new outer.inner1();
          stat.p();
    }inner is a non static member class even then " outer.inner nonStatic = new outer.inner();" working fine ?????????????

    class outer
            public  class inner{
            public void p()
                System.out.println("inside interface's non static member class");
    public class Client {                                           // (11)
        public static void main(String[] args) {                    // (12)
        outer.inner nonStatic = new outer.inner();
        nonStatic.p();
    }on compiling the above code the error message i got is
    "not an enclosing class: outer"
    the reason of this compilation error is "outer.inner nonStatic = new outer.inner();
    it should be "outer.inner nonStatic = new outer(). new inner();"
    now my question is
    interface outer
            public  class inner{
            public void p()
                System.out.println("inside interface's non static member class");
    public class Client {                                           // (11)
        public static void main(String[] args) {                    // (12)
        outer.inner nonStatic = new outer.inner();
        nonStatic.p();
    }on compiling the above code why compilation error is not coming??????????
    i think now it is more clear what i am asking

  • Static inner class causes deployment  on OC4J 10.1.2 to fail

    Hi,
    this issue has already been raised on OC4J 9.0.4 with J2SDK 1.4.2 (see EJB fails to compile - static inner class problem
    Recap: When referencing static inner classes in an EJB, the deployment fails. During the generation of the wrapper classes, a signature <package>.<outer class>.<inner class> gets converted to <package>.<outer class>$<inner class>, which is syntactically wrong. While the Java 1.4.1 compiler kindly ignores this syntax error, its 1.4.2 counterpart complains - and fails.
    @Oracle: When will this bug be fixed for OC4J 10.1.2?
    Best regards,
    Holger

    Holger,
    Don't static inner classes contradict the EJB specification?
    In any case, in answer to Andy's question: If you wish to file this as a bug, you can do so via the MetaLink Web site.
    [In fact, [i]MetaLink is your only option for submitting bugs for Oracle products -- as far as I know.]
    Good Luck,
    Avi.

  • Which one is better static inner classes or inheritance ?

    Hi,
    Consider following scenario,
    Class A does some database related work and Class B,C,D has more specific tasks for specific databases. For now B,C,D has more static information like driver name etc.
    1. I can either make class B,C,D as static inner classes OR
    2. classes B,C,D can extend class A.
    Case 1. makes it more flexible, if in future, B,C,D needs more than static methods.
    Case 2. can avoid complexity and cost of instantiating differnt objects based on differnt scenarios.
    Which approache is better in both ?
    Thanks

    Yes, I have seen abstract factory pattern , rather I have implemeted it at one place and in case 1. using abstract factory pattern is the way to initialize all classes.But my question is if I make all subclasses as a static inner classes, will it be better or efficient approach as compare to abstract factory pattern.Because Abstract factory patter adds more complications in code in turn it provides more flexibility.

  • How to dynamically load static (inner) class

    I have an urgnent question, any comments would be appricated.
    I have a static inner class definition.
    Class myObject
    public static class innerObject
    I want to dynamically load the static innerObject class such as
    Class c = Class.forName ( "myObject.innerObject" );
    innerObject t = ( innerObject ) c.newInstance();
    I can't do this as it give me ClassNotFound Exception, Do I need to load myObject first? any comments?
    The other alternative is that to define my myObject as having a static variable referencing the static class.
    Class myObject
    staic innerObject m_inner = new innerObject();
    public static class innerObject
    Is there any option in java allowing me to load a static variable?
    Many thanks
    Jay

    I can't do this as it give me ClassNotFound Exception,Use "myObject$innerObject" instead of "myObject.innerObject".
    Is there any option in java allowing me to load a
    static variable?What do you mean by that?

  • Static nested class VS non-static nested class ??

    we know static method can be called without creating an object and static variables are shared among objects.
    what is the difference between static nested class and non-static nested class ? When do we use them? what is the advantages of static nested class over non-static nested class in term of performance?

    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 use a static inner class?

    what's the implication of identifier "static" before an inner class.Thank you.

    not sure what implication is, due to my poor vocabulary. But here's an uuh... "example" of a static inner class:
    public class Example {
         static class AnotherClass {
    }There you have class "Example" with the static inner class "AnotherClass." If you wanted to use "AnotherClass" you would do something like:
    public class Whatever {
         Example.AnotherClass ac = new Example.AnotherClass();
    }I don't think I'm mistaken there, but if I am someone please correct me.

  • EJB fails to compile - static inner class problem

    I am using OC4J 9.0.4 and Sun JDK1.4.2 and EJBs fail to compile if they reference objects that contain static inner classes. However, they successfully compile under JDK1.4.1.
    For example, I have a class like below:
    public class ValueObject
    public static class Key
    private Key key;
    private String value;
    Any references to ValueObject.Key inside the EJB cause the EJB compiler to generate "ValueObject$Key" which is incorrect. JDK1.4.1 is more lenient than 1.4.2, and allows this error through.
    Is there a way around this problem other than reverting to JDK1.4.1?
    Regards,
    Andy

    The reason I don't want to move to JDK 1.4.1 is because of the memory leak in the StringBuffer.toString() method.
    Is there anywhere I can submit this as a bug?
    Regards,
    Andy

  • Why go for a static inner class than a regular static class

    Hello,
    What are the reasons to go for a static inner class? What benefits are available with a static inner class when compared to a static class?

    When a class is an integral part of another class, it doesn't make sense to create a top level class for it.
    Also there is no "static class" only static inner class.

  • Question about synchronized static function.

    Hi, everyone!
    The synchronized statement often deals with an object (called monitor).
    But a static function can be invoked without an object.
    So if a static function is declared as static, what is the function of
    static and synchronized here? Which lock it is using?
    Can you give me a simple expplanation?
    regards,
    George

    Hence try and avoid synchronizing static methods.
    Try and use non static method if you are doing
    multithreaded programming. That way you can have lockWell, I avoid static methods, not just when doing multithreading, but not for the reason you mention.
    objects which allow non interfering methods to be
    accessed in parallelThats easy to do with static methods anyway:
    class Foo
      static Object lock1 = new Object();
      static Object lock2 = new Object();
      static void method1()
         synchronized( lock1 )
      static void method2()
         synchronized( lock2 )
    }Maybe I just missunderstod you...

  • Static inner class

    class A{
    static class B{
    public void instanceMethod()
    System.out.println("instance method");
    class C{}How do I access the instanceMethod() of class B from class C ?

    But what does new A.B() mean.Static means that
    doesent run inside any instance of the class, rather it runs with class
    itself. So shouldnt it have been just A.new B()
    No, a static nested class is just a static member of the outer class.
    All other static members are accessible as Outer.innerMember and
    just so with that static nested class. Your proposal:A.new B()doesn't make sense because 'new' is not a static
    member of outer class A.
    kind regards,
    Jos

  • Confused about creation of inner class object of a generic class

    Trying to compile to code below I get three different diagnostic messages using various compilers: javac 1.5, javac 1.6 and Eclipse compiler. (On Mac OS X).
    class A<T> {
        class Nested {}
    public class UsesA <P extends A<?>> {
        P pRef;
        A<?>.Nested  f() {
            return pRef.new Nested();  // warning/error here
    Javac 1.5 outputs "UsesA.java:11: warning: [unchecked] unchecked conversion" warning, which is quite understandable. Javac 1.6 outputs an error message "UsesA.java:11: cannot select from a type variable", which I don't really undestand, and finally the Eclipse compiler gives no warning or error message at all. My question is, which compiler is right? And what does the message "cannot select from a type variable" means? "pRef", in the above code, is of a bounded type; why is the creation of an inner object not allowed?
    Next, if I change the type of "pRef" to be A<?>, javac 1.6 accepts the code with no error or warning message, while javac 1.5 gives an error message "UsesA.java:11: incompatible types" (concerning the return from "f" above). Similarly to javac 1.6, the Eclipse compiler issues no error message. So, is there something that has changed about generics in Java between versions 5 and 6 of the language?
    Thanks very much for any help

    Checkings bugs.sun.com, it seems to be a bug:
    http://bugs.sun.com/view_bug.do?bug_id=6569404

  • Question about view/controller/nib class design

    Assume you need to make an application with, let's say, 15 different views in total. There are two extreme design choices you can use to implement the app:
    1) Every single view has its own view controller and a nib file. Thus you end up with 15 controller classes and 15 nib files (and possibly a bunch of view classes if any of your views needs to be somehow specialized).
    2) You have only one controller which manages all the views, and one nib file from which they are loaded.
    AFAIK Apple and many books recommend going purely with option #1. However, going with this often results in needless complexity, large amounts of classes (and nib files) to be managed and complicated class dependencies, especially if some of the views (and thus their controllers) interact with each other or share something (something which would be greatly simplified if all these related views were handled by one single controller class).
    Option #2 also usually ends up being very complex. The major problem is that the single controller will often end up being enormous, handling tons of different (and usually unrelated) things (which is just outright bad design). This is seldom a good design, unless your application consists of only a few views which are closely related to each other (and thus it makes sense for one single controller class to handle them).
    (Option #2 also breaks the strictest interpretation of the MVC pattern, but that's not really something I'm concerned about. I'm concerned about simple design, not about following a programming pattern to the letter.)
    A design somewhere in between the two extremes often seems to be the best approach. However, since I don't have decades of Cocoa programming experience, I would like to hear some opinions about this subject matter from people with more experience on that subject. (I do have object-oriented programming experience, but I have only relatively recently started programming for the iPhone and thus Cocoa and its design patterns are relatively new to me, so I'm still learning.)

    Somehow I get the feeling that my question was slightly misunderstood.
    I was not asking "which one of these two designs do you think is better, option #1 or option #2?" I already said in my original post that option #2 is bad design (unless your application consists of just one or two views). That's not the issue.
    The issue is that from my own experience trying to adhere very strictly to the "every single view must have its own view controller and nib file" often results in needless complexity. Of course this is not always the case, but sometimes you end up having controller classes which perform very similar, if not even the exact same actions, resulting in code repetition. (An OO'ish solution to this problem would be to have a common base class for these view controllers where the common functionality has been grouped, but this often just adds to the overall complexity of the class hierarchy rather than alleviating it.)
    As an example, let's assume that you have a set of help screens (for example one help screen for each major feature of the app) and a view where you can select which help view to show. Every one of these views has, for example, a button to immediately exit the help system. If you had one single controller class managing these views, this becomes simpler: The controller can switch between any of the views and the buttons of each view (most of them doing the same things) can call back actions on this controller (eg. to return to the help selection or to exit the help screen completely). These help screens don't necessarily have any functionality of their own, so it's questionable what do they would need view controllers of their own. These view controllers would basically be empty because there's nothing special for them to do.
    View controllers might make it easy to use the navigation controller class, but the navigation controller is suitable mainly for utility apps but often not for things like games. (And if you need animated transitions between views, that can be implemented using the UIView animation features.)
    I also have hard time seeing the advantages of adhering strictly to the MVC pattern. The MVC pattern is useful in things like web servers, where MVC adds flexibility. The controller acts as a mediator between the database and the user interface, and it does so in such an abstract way that either one can be easily changed (eg. the "view", which normally outputs HTML, could be easily changed to a different "view" which outputs a PDF or even plain text, all this without having to touch the controller or the model at all). However, I'm not seeing the advantages of the MVC pattern in an iPhone app. It provides a type of class design, but why is it better than some other class design? It's not like the input and output formats of the app need to be changed on the fly (which is one advantage of a well-designed program using the MVC pattern).

  • Question about non-renewable subs

    Hi, we've just had our app submission rejected for a couple of reasons as our publication is bi-annual. So newsstand appears not to allow biannual publication under the Apple guidelines, not much we can do about that. However, even if we remove it from newsstand, if we want subscriptions we need to change them to the non-renewable type. So my question is, does DPS support non-renewable subscriptions? It's appears not to from the docs I've found.

    DPS does not support non-renewable subscription type.
    Choose auto-renewable in-app for subscriptions and Non-consumable in-app for the folios/issues you want to sell.

Maybe you are looking for

  • [SOLVED] What is the best way to use ZFS on linux-ck?

    Hi, I've recently gotten into ZFS to replace my Intel FakeRaid array I had set up for my /home folder. All is well under the stock kernel, but I'm running into issues while trying to run it under linux-ck. At boot systemd throws a fit, and in the eme

  • Please outline in steps for me...

    I have a presentation that will be presented to my class over a drop down projector thing. I will tap into it via vga plug. I have not yet tested it yet, only on my mac. Questions... 1) Will the presentation be fullscreen? When I press the play butto

  • How to create new folders in photos?

    I am sure this is simple but damned if I can find it.. how do you create new folders in Photos? I have camera roll but I want to create others..

  • Trying to buy app from iTunes and getting error code 1202

    Hi everyone. I am trying to buy an app from iTunes store but it is giving me error 1202 while starts the download. Anyone has any idea regarding this?

  • Having issues with KIK & AnyVideo for KIK with IOS7

    Can anyone give advice on any user end fixes for KIK? I am on iPad2 and KIK no longer has the AnyVideo icon and the camera function in KIK does not allow to switch from front to rear cameras. Other apps have similar issues and some just will no longe