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'

Similar Messages

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

  • Compiler bug with generics and private inner classes

    There appears to be a bug in the sun java compiler. This problem was reported against eclipse and the developers their concluded that it must be a problem with javac.
    Idea also seems to compile the example below. I couldn't find a bug report in the sun bug database. Can somebody tell me if this is a bug in javac and if there is a bug report for it.
    https://bugs.eclipse.org/bugs/show_bug.cgi?id=185422
    public class Foo <T>{
    private T myT;
    public T getT() {
    return myT;
    public void setT(T aT) {
    myT = aT;
    public class Bar extends Foo<Bar.Baz> {
    public static void main(String[] args) {
    Bar myBar = new Bar();
    myBar.setT(new Baz());
    System.out.println(myBar.getT().toString());
    private static class Baz {
    @Override
    public String toString() {
    return "Baz";
    Eclipse compiles and runs the code even though the Baz inner class is private.
    javac reports:
    Bar.java:1: Bar.Baz has private access in Bar
    public class Bar extends Foo<Bar.Baz>
    ^
    1 error

    As I said in my original post its not just eclipse that thinks the code snippet is compilable. IntelliJ Idea also parses it without complaining. I haven't looked at the java language spec but intuitively I see no reason why the code should not compile. I don't think eclipse submitting bug reports to sun has anything to do with courage. I would guess they just couldn't be bothered.

  • 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

  • Creating Private Inner Classes in Separate Files

    I sometimes find myself wanting to use private inner classes to do things, but then moving the classes to separate files and giving them package access just because I don't like having single large files.
    Is there a way to create private inner classes on a class but just save them in another file?
    Thanks,
    John

    For me, short file sizes usually make design structure
    more clear. This can make maintenance easier. It can
    also make browsing the code easier, even if you have a
    good editor or IDE. It is also less intimadating
    psychologically (for me, anyway) to work with a number
    of small files, each one with a distinct purpose, than
    it is to open up a monster, even if the monster does
    represent a coherent design unit in some sense. I
    think this psychological impact may be more important
    than most people give it credit for.The psychological impact is lessened if you use an IDE like VisualAge (where only one method at a time is generally displayed) or use the "Show Source Of Selected Element Only" option in Eclipse.
    It's one thing to say a method should be short and a class should have as few methods as possible. Those forces reduce complexity and ease maintenance. It's another to say a source file should be short. A source file is just a storage artifact; source code could be stored in a database without changing how the programmer interacts with it. The fact that the standard java compiler requires the implementation of nested classes to be stored inside the source file of their containing class is a minor inconvenience. Don't let it discourage you from using inner classes when they make sense. The design should not be driven by source file size considerations.
    >
    But you have added code only with the sole intent of
    making a source file smaller. If Java had amechanism
    for storing nested classes in other files youwouldn't
    do this. My point below was that you shouldn't let
    source file size override the decision to use anested
    class.Why shouldn't I let it? There are plenty of
    non-trivial benefits (the ones I gave above, for
    starters) to working with smaller files.Because all of those benefits can be gained from using a decent IDE. Eclipse is free. It can show only the current method and it can collapse nested classes.
    You say "If
    Java had a mechanism...." Well, I could answer: It
    does have such a mechanism, and that mechanism is
    packages.Packages are not a mechanism for creating private inner classes in separate files. Eclipse has a mechanism for making the fact that they reside in the same source file a non-issue.
    >>
    I am not being cavalier. I have no argument, onlyan
    opinion.Again, you are perfectly entitled to your opinion.
    But if it is truly an opinion, and nothing more, why
    bother telling me about it. You might as well post
    your favorite color. It is the reasons for your
    opinion that interest me, and you still have not
    really given any.I have had lengthy arguments about the issue of method and class size. Like I said before, I prefer very small classes and methods. I also think the number of nested classes should be as small as possible. But I have no problem with large files. Files are just one way to organize source code. The size of the things in the files matters, not the files themselves.

  • Private inner class

    I have a private inner class , the methods and constructor of this inner class should be private or default ?Please explain me what is the right method and constructor access modifier I should use to private inner classes .

    paulcw wrote:
    I believe that if you make the constructor private, nothing can instantiate it.Not true for an inner class.
    Re the original question: I'm not sure it really matters here, but I've not seen a canonical answer to this.

  • Private inner class and static private inner

    Hi,
    I understand the concept and usage of inner classes in general.
    When should we go for a private inner class and when for a static private inner class? I tried searching but it wasn't of much help.
    Basically I need to design a caching solution in which I need to timestamp the data object. After timestamping, data will be stored in a HashMap or some other collection. I'm planning to use a wrapper class (which is inner and private) which holds the data object and timestamp. I can make the program work by using either normal inner class or static inner class, however would like to know which is better in such case. Also If I can get some general guidelines as to when to use a staic inner class and when to use a normal inner class, it would help me.
    Thanks in advance.

    user1995721 wrote:
    When should we go for a private inner class and when for a static private inner class?
    I can make the program work by using either normal inner class or static inner class, however would like to know which is better
    If I can get some general guidelines as to when to use a static inner class and when to use a normal inner class, it would help me.Making the inner class static is helpful in that it limits visibility.
    If the inner class needs to access non-static fields or methods from the containing class instance
    the inner class has to be non-static.

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

  • Private inner classes

    I'm trying to complete a "turn the lightbulb on and off" program, but when I try to draw circle2 in the
    ButtonListener class I get an error message cannot find symbol. This is in reference to the Graphics
    variable "page" created in the paintComponent method below. Shouldn't the inner class, private or
    public inherit all data variables including objects from the parent class, in this case, the Bulb class? The code is below.
    By the way, this IS NOT a school assignment so any help would be appreciated. I'm just trying to learn
    this language.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Bulb extends JPanel
         private JButton push;
         private Circle circle, circle2;
         private final int DIAMETER = 100;
         private final int X = 10;
         private final int Y = 10;
         public Bulb()
              circle = new Circle(DIAMETER, Color.white, X,Y);
              circle2 = new Circle(DIAMETER, Color.yellow, X, Y); // to separate class
              push = new JButton("Turn on the Bulb");
              push.addActionListener(new ButtonListener());
              add(push);
              setPreferredSize(new Dimension(500, 500));
              setBackground(Color.black);
         public void paintComponent(Graphics page)
              super.paintComponent(page);
              circle.draw(page);
    private class ButtonListener implements ActionListener
              public void actionPerformed(ActionEvent event) //PROBLEM AREA. I GET ERROR MESSAGE STATING
    // "CANNOT FIND SYMBOL" IN REFERENCE TO VARIABLE "PAGE."
    // I THOUGHT THE INNER CLASS INHERITS ALL DATA FROM
    // PARENT CLASS SUCH AS "PAGE."
                   circle2.draw(page);
    }

    There are fields, which are associated with either a class or an object (and thus live in the heap in an object on the heap), and there are local variables, which are associated with methods and threads (i.e., a method invoked within a thread, and which thus live on the stack).
    They're not the same thing.
    You can't use a local variable in your paintComponent method in a different method.
    Anyway you're designing your class wrong. Think model-view-controller. You have the model: a bunch of state and possibly behavior that represents the thing being seen, modified, and displayed. You have the view, which is how you see the model. And you have the controller, which modifies the model.
    Your event handlers are part of the controller. They should change the model.
    Your paintComponent method is part of the view.
    So the event handlers should change some data, e.g., add a note that a circle should be displayed.
    Then your paintComponent method should look at the data and act accordingly -- e.g., see that there's a circle to be displayed, and display it.

  • Creating a generic class with a constructor that takes an array of objects

    I am relatively new to java and want to build a quick utility class that can generate a Run Length Encoding of any object. The idea is to take an array of objects of type "O" and then encode a string of objects that are "equal" to each other as an integer that counts the number of such equal instances and a single copy of the instance. This has the potential to very quickly reduce the size of some objects that I want to store. I would like to implement this class as a generic.
    public class RunLengthEncoding<O> {
         private class RLEPair {
              private int length;
              private O object;
         public RunLengthEncoding(O[]) {
    }As you can see, I need to make a constructor that takes an array of type "O". Is this possible to do? I can't seem to find the right syntax for it.
    Thanks,
    Sean

    Sorry. Obvious answer:
    public RunLengthEncoding(O[] oarray) {Again, sorry for the noise.

  • How to reference an inner class with @link?

    Hi,
    Let's assume we have a class Test with an inner class namned InnerTest. If I want to put a @link to a method in InnerTest in another java-file, what do I write?
    To reference a method in Test, I write:
    {@link com.company.Test#method}
    My first thought when referencing the inner class' method was to just write:
    {@link com.company.Test.InnerTest#method}
    but this doesn't seem to be the correct way.
    Any help is greatly appreciated! Thank you in advance.

    You're calling the method in the inner class the right way.
    You're probably experiencing bugs with links.
    I don't know what version you're using, but 1.4.0 and
    1.4.1 have some severe bugs. Please see another
    thread in this forum entitled:
    "Some {@link} tags do not seem to generate hyperlinks"
    -Doug Kramer
    Javadoc team

  • Default class with public constructor - why?

    Noticed some code that had a class with package-level access and a public constructor - wondered what the benefit/use of that would be... Thanks!

    GarudaJava wrote:
    Noticed some code that had a class with package-level access and a public constructor - wondered what the benefit/use of that would be... Thanks!If the class itself doesn't need to be exposed, but it implements some interface, and is assumed to have a public no-arg consturctor, it could be created reflexively. This is a contrived situation, but it's the only one I can think of in Java where that'd be useful.
    package foo;
    class Foo implements SomeInterface {
      public Foo() {
    package factory;
    class Factory {
      public static SomeInterface create(Class<? extends SomeInterface> clazz) { // not sure if I got the generics right, but they're incidendtal to the example
        return clazz.newInstance();
    package foo;
    import factory.Factory;
    public class Bar {
      public void bar() {
        SomeInterface si = Factory.create(Foo.class);
        si.doStuff();
    }Like I said, pretty contrived, and I can't think of a real-world use case that matches it offhand, but structurally it'd look something like that.
    You could also maybe imagine that the factory package might do more than just create and return an instance. It might create it and use that SomeInterface type for its own ends.

  • Creation of a static class with private methods

    I'm new to java programming and am working on a project where I need to have a static class that does a postage calculation that must contain 2 private methods, one for first class and one for priority mail. I can't seem to figure out how to get the weight into the class to do the calculations or how to call the two private methods so that when one of my other classes calls on this class, it retrieves the correct postage. I've got all my other classes working correct and retrieving the information required. I need to use the weight from another class and return a "double". Help!!!
    Here's my code:
    * <p>Title: Order Control </p>
    * <p>Description: Order Control Calculator using methods and classes</p>
    * <p>Copyright: Copyright (c) 2002</p>
    * <p>Company: Info 250, sec 001, T/TH 0930</p>
    * @author Peggy Blake
    * @version 1.0, 10/29/02
    import javax.swing.*;
    public class ShippingCalculator
    static double firstClass, priorityMail;
    //how do I get my weight from another class into this method to use??? not sure I understand how it works.
    public static double ShippingCalculator(double weight)
    String responseFirstClass;
    double quantity, shippingCost;
    double totalFirstClass, firstClass, priorityMail, totalShipping;
    double priorityMail1 = 3.50d;//prioritymail fee up to 1 pound
    double priorityMail2 = 3.95d;//prioritymail fee up to 2 pounds
    double priorityMail3 = 5.20d;//prioritymail fee up to 3 pounds
    double priorityMail4 = 6.45d;//prioritymail fee up to 4 pounds
    double priorityMail5 = 7.70d;//prioritymail fee up to 5 pounds
    quantity = 0d;//ititialization of quantity
    // weight = 0d;//initialization of weight
    // shippingCost = 0d;
    //calculation of the number of items ordered..each item weights .75 ounces
    quantity = (weight/.75);
    if (quantity <= 30d)
    //add 1 ounce to quantities that weigh less than 30 ounces
    weight = (weight + 1);
    else
    //add 2 ounces to quantities that weigh more than 30 ounces
    weight = (weight + 2);
    if (weight > 80d)
    //message to orderclerk ..order over 5 lbs, cannot process
    JOptionPane.showMessageDialog(null, "Order exceeded 5 lbs, cannot process");
    //exit system, do not process anything else
    System.exit (0);
    else
    if (weight < 14d)
    //send message to customer: ship firstclass or priority, y or n
    responseFirstClass = JOptionPane.showInputDialog(null, "Ship first class? y or n?");
    if (responseFirstClass.equals("y"))
    //compute FirstClass shipping cost
    totalFirstClass = ((weight - 1) * .23d) + .34d;
    firstClass = totalFirstClass;
    else
    //compute PriorityMail cost for orders less than 14 ounces
    priorityMail = (priorityMail1);
    else
    if (weight <=16d)
    //compute totalshipping for orders up to 16 ounces
    priorityMail = (priorityMail1);
    else
    if (weight <=32d)
    //compute totalshipping for orders up to 32 ounces
    priorityMail = (priorityMail2);
    else
    if (weight <=48d)
    //compute totalshipping for orders up to 48 ounces
    priorityMail = (priorityMail3);
    else
    if (weight <= 64d)
    //compute totalshipping for orders up to 64 ounces
    priorityMail = (priorityMail4);
    else
    //compute totalshipping for orders up to 80 ounces
    priorityMail = (priorityMail5);
    priorityMail = 0d;
    firstClass = 0d;
    firstClassMail ();
    priorityMailCost ();
    //I think this is where I should be pulling the two methods below into my code, but can't figure out how to do it.
    shippingCost = priorityMail + firstClass;
    return (shippingCost);
    }//end method calculate shipping
    private static double firstClassMail()//method to get first class ship cost
    return (firstClass);
    }//end method firstclass shipping
    private static double priorityMailCost()//method to get priority mail cost
    return (priorityMail);
    }//end method priorityMail
    }//end class shipping calculator

    public class A {
    public String getXXX () {
    public class B {
    A a = new A();
    public void init () {
    a.getXXX();
    }

  • Private inner classes, should this compile:

    class Outer
    &nbsp&nbsp&nbsp&nbspclass InnerA;
    &nbsp&nbsp&nbsp&nbspclass InnerB;
    &nbsp&nbsp&nbsp&nbspclass InnerA
    &nbsp&nbsp&nbsp&nbsp{
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspInnerB* m_inner;
    &nbsp&nbsp&nbsp&nbsp};
    &nbsp&nbsp&nbsp&nbspclass InnerB
    &nbsp&nbsp&nbsp&nbsp{
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspInnerA* m_inner;
    &nbsp&nbsp&nbsp&nbsp};
    The Sun Studio 8 C++ compiler says that InnerB is not accessible from InnerA and vica-versa.
    However, both classes are members of the outer class and I would think that just like member functions, they should have access to all the declarations (prviate or not) in the outer class.
    Is the compiler correct to complain about this?
    Kind Regards,
    Dave.

    the current wording of the standard favours the Sun' s interpretation.
    gcc have gone with assuming that core language defect report 45 will be accepted which would allow this.
    see http://anubis.dkuug.dk/jtc1/sc22/wg21/docs/cwg_defects.html#45 .
    /lib

  • Extending classes with private methods?

    my understanding of extending classes is that you gain all the functions and methods of that class thus You could over ride any one of them. How ever I am confused on weather or not you inherit and can over ride private methods of the class you are extending or if you have to have all methods public in an extended class.
    hope that makes sense, an example can bee seen bellow.
    package
         public class Class1
              public function apples():void
                   //some code
              private fnctuin bananas():void
                   //more code
    package
         public class Class2 extends Class 1
              override public function apples():void
                   //i changed code
              //can I over ride bananas?

    you can only override methods that would be inherited.  a private method won't be inherited:
    http://www.kirupa.com/forum/showthread.php?223798-ActionScript-3-Tip-of-the-Day/page5

Maybe you are looking for