Enclosing class calling private constructor of private member class

Hi all,
I have this question concerning member classes and privtae constructors.
public class MyTest {
    private class Inner {
        private Inner() {
            System.out.println("Why Am I here!??");
    public MyTest() {
        Inner a = new Inner();
    public static void main(String[] s) {
        MyTest z = new MyTest();
}It doesn't work for my JDK SE 1.3.3, build 1.3.1-b24.
It works for many other versions.
Can somebody kindly enlighten me, should this code work?
I really didn't think that it should, but it did!

I am sorry. It was actually my jikes 1.15 that was causing the problem.
After some research, I found out that my problem arose out of my understanding of OO concepts, or rather, the meaning of access modifiers in Java.
I had thought that nobody can access a private variable/method of class except the class itself. Apparently, this is not so. The access modifiers apply to the class themselves and not the object. Thus explaining why an object can access the private variables/methods of another object of the same class.
Actually, it's not really the case here. The Java language specs states that the inner class has total access to the enclosing class, but I could not find any word on enclosing class access to inner classes in the specs.
As for Jikes, I really hope they will fix it soon. I like it a lot as it is significantly faster than javac for everything I have done so far.
cheers!

Similar Messages

  • Defining a Private Constructor in private section of the class?

    In the exercises of ABAP OOPs book, I have the found following question.
    Q. A private instance constructor (instantiation only by the class itself) can be defined in the private section.
    True or False
    The answer provided in the book is "True". But actually, its not possible to define a constructor in a private or protected section, regardless of the constructor visibility.
    Can anyone help me in this question?

    from the ABAP help:
    The statement METHODS constructor for the declaration of the instance constructor of a class declared with the adition CREATE PRIVATE, can not only be listed in the public, but also in the protected or private visible area. This allows the use of components, which have been declared there, in the interface of the constructor.
    the problem might be your SAP system version. I have verified this on Netweaver 7.00.
    best regards,
    J.N.N

  • Why do we need private static method or member class

    Dear java gurus,
    I have a question about the use of private and static key words together in a method or inner class.
    If we want to hide the method, private is enough. a private static method is sure not intended to be called outside the class. So the only usage I could see is that this private static method is to be called by another static method. For inner class, I see the definition of Entry inner class in java.util.Hashtable, it is static private. I don't know why not just define it as private. Could the static key word do anything better.
    Could anybody help me to clear this.
    Thanks,

    What don't you get? Private does one thing, andstatic does >something completely different.
    If you want to listen to music, installing an airconditioner doesn't help>
    Hi, if the private keyword is the airconditioner, do
    you think you could get music from the static keyword
    (it acts as the CD player) in the following codes:You're making no sense and you're trying to stretch the analogy too far.
    Private does one thing. If you want that thing, use private.
    Static does something completely different and unrelated. If you want that thing, use static.
    If you want both things, use private static.
    What do you not understand? How can you claim that you understand that they are different, and then ask, "Why do we need static if we have private"? That question makes no sense if you actually do understand that they're different.

  • Instantiate a Class through a constructor argument of another class.

    public function LevelManager(owner:Home)
                                  _owner = owner;
    In my LevelManager Class I have the above code in the constructor. Home is another Class which is not instantiated anywhere with the new keyword. It is merely a parameter in the constructor and then passed into the body and assigned to a local variable. I didn't know you could instantiate a class through a function parameter. Is that right???
    Cheers in advance.

    Well, I know Amy is big on design patterns and she is going to slap me but I am the guy who is not a big fun of DPs in regular Flash applications. I have many reasons to dislike them.
    I am not against DPs in principal. In collaborative environments (big teams) or in situations when software is developed for industrial consumption or as partially closed frameworks - it makes sense. Otherwise - they are just possible solutions and reference point at best. In Flash they frequently are major silly overkills. They are more of academic than practical value contrary to what people tend to believe.
    Design patterns are possible solutions that developers came up with heuristically base on the problems they needed to solve - not vice versa. Problems do not dictate design patterns.
    There is a strong tendency among DPs proponents and followers to make DPs self-fulfilling prophecies. Instead of conceptualizing of particular application needs developers often are searching for DP first and then try to squeeze logic into a particular or a group of several design patterns.
    If a person is taught that DPs is the only way to go - there is a great danger of killing creativity and the thought process.
    I strongly believe that what makes a star programmer is the ability to conceptualize the project, model it well and only then find coding solutions based on language capacities. And to question any suggestions in favor of current task efficiencies.
    By the same token, if your painting doesn't need color red - why use it? This is another thing that happens often - developers implement something that is actually not needed.
    Code is cheap! When project is well conceived and modeled - coding takes very little time. One ends up with his/her own "design pattern" that may or may not fall into one of DPs that is articulated already.
    Also, there is a great deal of activism around DPs that, as with any activism, forms an ideology that is full of misleading simplifications.
    First one is that OOP is equated to DPs usage. This is totally dangerously  untrue!!!
    Another one is you mentioned. Spaghetti coding is not the only alternative to design patterns. In other words, if one doesn't use DP - it absolutely doesn't mean person is engaged in spaghetti coding. And vice versa - DP does not shield program from spaghetti coding. I have seen DP warriors going crazy with spaghetti coding although DP was implemented to the tee.
    Another example of misconception is that DP proponents always carry banners of decoupling and modularization. Be very skeptical when someone gives you this shpeal. Modularization is easy to conceal for "propaganda" purposes and it is comfortable not to think about when DPs are used (especially MVC concept). Since this is just a concept - there are no real checks and balances.
    Decoupling, on the other hand, is not that easy to shove down someone's throat. Decoupling can be actually calculated - this is where a lot of idealistic beliefs that someone's code is well decoupled because of the DP fails miserably. Not because of DP itself but because of implementation. Well, sometimes pattern too.
    See, there is no black and white again.
    My point is that DPs do not protect anyone from any kind of challenges or mistakes as they don't make a better programmer. They can make one a disciplined follower but not a real creator (not that everyone must be the Creator).
    If not used properly DPs may be a ground for crappy inefficient un-scalable application as much as any other approach.
    And the last thing. I said that DPs are special suspects in Flash. This is because ActionScript and Flash are already limited frameworks that force us into thinking in MVC terms. This is just a nature of the beast. To attempt to warp it up into another MVC framework looks like a self-indulgent irrelevant academic activity to me.
    And I did not even mentioned practicalities of the target environments we develop our applications for.

  • Call a method of a class in a constructor of another class?

    Is this good programming or should i do it in another way?
    Consider an ordering system, where I have three classes, "Booking", "Table" and "Customer.
    My idea is to create a booking assigned to a table and a customer, the fields in the booking class is a Customer and a Table and the constructor assigns values to these field.
    In my Table class i have a method that books the table "bookTable(Customer customer)" and sets the availablility to 'false'.
    So my question is, is it good programming to call the method 'bookTable()' in the table class from the constructor of the Booking class? Or should i do it in another way?
    Edited by: DJHingapus on Jul 6, 2009 5:12 AM

    This sounds the wrong way around. What is the return value of bookTable(Customer)?
    I'd expect it to return a Booking object that it creates.
    Generally, you want the constructor to do as little as possible (while still only ever returning in a valid state, of course!).
    The problem you can get when you call other methods is that you introduce the possibility of other objects getting access to your object before the constructor has finished running (i.e. before the object is completely initialized). This can lead to nasty problems that are hard to find and debug.

  • Even i call this() paramerterised constuctor in my class, Is super class su

    Even i call this() paramerterised constuctor in my class, Is super class super() parameter less constuctor invokes?
    I have excuted the following program. And result will be as follows:
    Grandparent() constructor
    Parent 25 constructor
    Parent() constructor
    Child() constructor
    The program is below:
    class ConstructorChain {
    public static void main(String[] args) {
    Child c = new Child();
    class Child extends Parent {
    Child() {
    System.out.println("Child() constructor");
    class Parent extends Grandparent {
    Parent() {
    this(25);
    System.out.println("Parent() constructor");
    Parent(int x) {
    System.out.println("Parent(" + x + ") constructor");
    class Grandparent {
    Grandparent() {
    System.out.println("Grandparent() constructor");
    for this my excepected answer is
    Parent 25 constructor
    Parent() constructor
    Child() constructor
    because in parent class i defined this() constructor so, as my undersatnd is it never call Grand Parent Constructor as it is default parameterless constructor.
    please Advise me
    Aruna

    You can't initialize a class without it's super classes constructor being run. So even if you call another constructor (of the same class), the parent classes constructor will still be called.

  • Constructor in my servlet class

    Can i write a constructor in my servlet class inherited from HttpServlet.
    eg:
    class myServlet extends HttpServlet
    myServlet()
    doGet(......)
    }

    And who will call the derived class no args constructor?
    Remember Servlet classes are managed by the container which is responsible for initiating the servlets and calling appropriate life cycle methods. The container initiates the Servlet using the no args constructor. For all practical purposes you would choose the init() method rather than the constructor for initialization logic.
    ram.

  • Know the name of class caller...

    Hi... it has a way to know the name of class caller... that is the class name than use a methodA of a ClassA and in the methodA know the name of class than is using this method...

    Hi... it has a way to know the name of class caller...
    that is the class name than use a methodA of a ClassA
    and in the methodA know the name of class than is
    using this method...
    And the requisite question - why?

  • Private inner class with private constructor

    I read that if constructor is public then you need a static method to create the object of that class.
    But in the following scenario why I am able to get the object of PrivateStuff whereas it has private constructor.
    I am messing with this concept.
    public class Test {
          public static void main(String[] args) {          
               Test t = new Test();
               PrivateStuff p = t.new PrivateStuff();
          private class PrivateStuff{
               private PrivateStuff(){
                    System.out.println("You stuff is very private");
    }

    A member (class, interface, field, or method) of a reference (class, interface, or array) type or a constructor of a class type is accessible only if the type is accessible and the member or constructor is declared to permit access:
    * Otherwise, if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. [Java Language Specification|http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.6.1]
    Your main method is within the body of the top level class, so the type (the inner class) and method are accessible.
    eg:
    class ImInTheSameSourceFileAsInnerAccessTest {
        public static void main(String[] args) {          
            InnerAccessTest t = new InnerAccessTest();
            InnerAccessTest.PrivateStuff p = t.new PrivateStuff();
    public class InnerAccessTest {
          public static void main(String[] args) {          
               InnerAccessTest t = new InnerAccessTest();
               PrivateStuff p = t.new PrivateStuff();
          private class PrivateStuff{
               private PrivateStuff(){
                    System.out.println("You stuff is very private");
    }Result:
    $ javac -d bin src/InnerAccessTest.java
    src/InnerAccessTest.java:4: InnerAccessTest.PrivateStuff has private access in InnerAccessTest
    InnerAccessTest.PrivateStuff p = t.new PrivateStuff();
    ^
    src/InnerAccessTest.java:4: InnerAccessTest.PrivateStuff has private access in InnerAccessTest
    InnerAccessTest.PrivateStuff p = t.new PrivateStuff();
    ^
    2 errors
    Edited by: pm_kirkham on 20-Jan-2009 10:54 added example of 'in the same source file'

  • Abstract Classes vs Private Constructor

    Hopefully this doesn't make me sound to naive
    If we have a super class called food, and subclasses chocolate, chicken, cereal and so on then its clear we dont want to make instances of the super class food correct? So we can make this class an abstract class
    What are the benefits of making a class abstract over making a constructor private and in what circumstance would it be beneficial to do one over the other?
    Thanks, and sorry for a poor example!
    Edited by: compSciUndergrad on Apr 22, 2009 4:53 AM

    wrybread wrote:
    Also, Corlettk -
    Excellent point regarding prudent use of interfaces; thank you. If you read this, I'd appreciate any comment you have on how conservative programmers need to be in designing an interface. It seems to me that if I'm uncertain whether or not to include a certain member in the interface, I should omit it or include it elsewhere (perhaps in an interface all its own, or in an abstract super if that's applicable).
    Let me know if you want me to open this as a new thread; I'm just looking for your take on this topic. -- Thank you!Obviously, there's no right answer. Each deisgn must be assessed on a case-by-case basis. Every design presents new and interesting problems.
    I'm no OO guru... what I do know is that you can make some very nasty mistakes, thanks to experience of maintaining a fairly poorly written (first in the organisation) large java project.
    I'm of the opinion that interface should define an aspect of behaviour... If the Sun GODS had there time again they'd do java.io would be full of interfaces... Closeable, Openable, Readable, Writable, Printable... etc etc etc.
    Please remember that a class (or group of classes) can implement multiple interfaces... and an interface can extend multiple interfaces... So java supports "multiple type inheritance" as apposed to C++'s "multiple implementation inheritance".
    If you need an "aglomerate" interface as the type for a collection then assemble one from your premade "set of aspects"... eg: Input extends Openable, Closeable, Readable...
    package forums;
    interface AnInterface
      public void a();
    interface AnotherInterface
      public void b();
    interface AglomerateInterface extends AnInterface, AnotherInterface
      public void c();
    class AglomerateImpl implements AglomerateInterface
      public static void main(String[] args) {
        try {
          System.out.println("Hello World!");
        } catch (Exception e) {
          e.printStackTrace();
      public void a() {}
      public void b() {}
      public void c() {}
    }PS: You wouldn't normally define multiple interfaces and an implementation all in one file... sort of defeats the whole purpose really... and in fact you can't as soon as you make the interfaces public, which they need to be to be any use.
    Make sense?

  • Instantiate class with a private constructor

    How do you call a class that happens to have a private constructor. how would one instantiate such a class? Generally constructors are supposed to be public.
    But in many cases the constructor for a class can be private, so how to call such a class?

    khurrumnas wrote:
    I dont think you would need to provide such a method (newInstance()), its there for you already in Class Class, so its suffice to just call
    newInstance() to get an instance of class that happens to have a private constructor, in the simplest case.False, as jverd rightly mentioned. Example: public class Foo {
        public static void main(String[] args) {
            Exception expectedException = null;
            try {
                Bar b = (Bar) Class.forName("Bar").newInstance(); // throws Exception
            } catch (Exception e) {
                expectedException = e;
            assert expectedException instanceof IllegalAccessException;
    class Bar {
        private Bar() {}
    }As mentioned several times now, one can get around this restriction, but it's considered poor form to do so.
    ~

  • Class with private constructor can be extended or not

    Hi All,
    I have a doubt.
    if a class has private constructor and there are some methods in this class.Can this class be extended and if yes how can we call its method in subclass?
    Thanks
    Sumit

    Karanjit wrote:
    If a class contains only private constructors, then it cannot be extended.Err... not the whole story!
    public class Sabre20090603a
        static class Fred extends Sabre20090603a
            Fred()
                super();
        private Sabre20090603a()
    }

  • Why can't classes with private constructors be subclassed?

    Why can't classes with private constructors be subclassed?
    I know specifying a private nullary constructor means you dont want the class to be instantiated or the class is a factory or a singleton pattern. I know the workaround is to just wrap all the methods of the intended superclass, but that just seems less wizardly.
    Example:
    I really, really want to be able to subclass java.util.Arrays, like so:
    package com.tassajara.util;
    import java.util.LinkedList;
    import java.util.List;
    public class Arrays extends java.util.Arrays {
        public static List asList(boolean[] array) {
            List result = new LinkedList();
            for (int i = 0; i < array.length; i++)
                result.add(new Boolean(array));
    return result;
    public static List asList( char[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Character(array[i]));
    return result;
    public static List asList( byte[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Byte(array[i]));
    return result;
    public static List asList( short[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Short(array[i]));
    return result;
    public static List asList( int[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Integer(array[i]));
    return result;
    public static List asList( long[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Long(array[i]));
    return result;
    public static List asList( float[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Float(array[i]));
    return result;
    public static List asList( double[] array) {
    List result = new LinkedList();
    for (int i = 0; i < array.length; i++)
    result.add(new Double(array[i]));
    return result;
    // Now that we extend java.util.Arrays this method is not needed.
    // /**JCF already does this so just wrap their implementation
    // public static List asList(Object[] array) {
    // return java.util.Arrays.asList(array);
    public static List asList(Object object) {
    List result;
    Class type = object.getClass().getComponentType();
    if (type != null && type.isPrimitive()) {
    if (type == Boolean.TYPE)
    result = asList((boolean[])object);
    else if (type == Character.TYPE)
    result = asList(( char[])object);
    else if (type == Byte.TYPE)
    result = asList(( byte[])object);
    else if (type == Short.TYPE)
    result = asList(( short[])object);
    else if (type == Integer.TYPE)
    result = asList(( int[])object);
    else if (type == Long.TYPE)
    result = asList(( long[])object);
    else if (type == Float.TYPE)
    result = asList(( float[])object);
    else if (type == Double.TYPE)
    result = asList(( double[])object);
    } else {
    result = java.util.Arrays.asList((Object[])object);
    return result;
    I do not intend to instantiate com.tassajara.util.Arrays as all my methods are static just like java.util.Arrays. You can see where I started to wrap asList(Object[] o). I could continue and wrap all of java.util.Arrays methods, but thats annoying and much less elegant.

    Why can't classes with private constructors be
    subclassed?Because the subclass can't access the superclass constructor.
    I really, really want to be able to subclass
    java.util.Arrays, like so:Why? It only contains static methods, so why don't you just create a separate class?
    I do not intend to instantiate
    com.tassajara.util.Arrays as all my methods are static
    just like java.util.Arrays. You can see where I
    started to wrap asList(Object[] o). I could continue
    and wrap all of java.util.Arrays methods, but thats
    annoying and much less elegant.There's no need to duplicate all the methods - just call them when you want to use them.
    It really does sound like you're barking up the wrong tree here. I can see no good reason to want to subclass java.util.Arrays. Could you could explain why you want to do that? - perhaps you are misunderstanding static methods.
    Precisely as you said, if they didn't want me to
    subclass it they would have declared it final.Classes with no non-private constructors are implicitly final.
    But they didn't. There has to be a way for an API
    developer to indicate that a class is merely not to be
    instantiated, and not both uninstantiable and
    unextendable.There is - declare it abstract. Since that isn't what was done here, I would assume the writers don't want you to be able to subclass java.util.Arrays

  • Final class and private constructor

    Whats the difference in a final class and a class with private constructot?
    If we can make a class non-extendable by just giving private constructor then whats the advantage of final class? (I know final is very useful for many other things but just want to get info in this contaxt)

    You can extend a class with a private constructor,I'm not sure about that. The compiler will complain.
    KajThat depends on the signature of the private constructor.
    If it's the no-arg constructor and you don't declare another constructor which you explicitly call from your derived class you will indeed get an error.
    If however you never call it (and there's no way it can implicitly get called) from a derived class there should be no problem.
    class Private1 {
         private int q;
         private Private1() {
         public Private1(int i) {
              q = i;
         public void print() {
              System.out.println(q);
    public class Public1 extends Private1 {
         public Public1() {
              super(1);
         public static void main(String[] args) {
              new Public1().print();
    }for example compiles and runs perfectly.
    But remove the call "super(1);" from the constructor and it will fail to compile.

  • Help: Factory Class using Inner Class and Private Constructor?

    The situation is as follows:
    I want a GamesCollection class that instantiates Game objects by looking up the information needed from a database. I would like to use Game outside of GamesCollection, but only have it instantiated by GamesCollection to ensure the game actually exist. Each Game object is linked to a database record. If a Game object exist, it must also exist in the database. Game objects can never be removed from the database.
    I thought about making the Game object an inner class of GamesCollection, but this means that Game class constructor is still visible outside. So what if I made Game constructor private? Well, now I can't create Game objects without a static method inside Game class (static Object factory).
    Basically what I need is a constructor for the inner Game class accessible to GamesCollection, but not to the rest of the world (including packages). Is there a way to do this?

    leesiulung wrote:
    As a second look, I was initially confused about your first implementation, but it now makes more sense.
    Let me make sure I understand this:
    - the interface is needed to make the class accessible outside the outer classBetter: it is necessary to have a type that is accessible outside of GameCollection -- what else could be the return type of instance?
    - the instance() method is the object factory
    - the private modifier for the inner class is to prevent outside classes to instantiate this objectRight.
    However, is a private inner class accessible in the outer class? Try it and see.
    How does this affect private/public modifiers on inner classes?Take about five minutes and write a few tests. That should answer any questions you may have.
    How do instantiate a GameImpl object? This basically goes back to the first question.Filling out the initial solution:
    public interface Game {
        String method();
    public class GameCollection {
        private static  class GameImpl implements Game {
            public String method() {
                return "GameImpl";
        public Game instance() {
            return new GameImpl();
        public static void main(String[] args) {
            GameCollection app = new GameCollection();
            Game game = app.instance();
            System.out.println(game.method());
    }Even if you were not interested in controlling game creation, defining interfaces for key concepts like Game is always going to be a good idea. Consider how you will write testing code, for example. How will you mock Game?

Maybe you are looking for

  • Animated Gif as an ICNS

    Hi Everyone, please could you help me, i am trying to change my External USB hard drive icon to a Animated gif with a flashing blue light i have created the gif and put it through img2icns but that doesn't seem to work, so my question is 1 if it is p

  • Creating a new User in BO 4.1

    Hello everyone, When I am creating a new user and check the security I find that Administrator group is automatically inherited. Where is it inheriting the admin group from.  I cannot remove it since it is inherited. Any idea where it is coming from

  • Will it cost me money to go in and get my OS X repaired or reinstalled on my Macbook Pro?

    I bought a MacBook Pro off of Craigslist and at first the computer would not allow me to log into my apple id due to the fact that we were not the original buyer of the computer (at least that is the message we got from it). We turned off the compute

  • Installing APEX (first timer)

    Hi, From http://www.oracle.com/technology/products/database/application_express/download.html, I downloaded the file "Oracle Application Express 3.2.1" upon unzipping it does not seem to have any executable file. All I could find are various text fil

  • QRFC not updating after TO processed in LX47

    We have delayed update configured in the system. During transfer order confirmation, the TO does not update due to user locking and we use LX47 to process the delayed updates for TOs. But the subsequent TO_LATE entry for that TO in SMQ1 qRFC monitor