Private constructor

Hello,
For security reasons I am trying to set up a class so that only a static method within that class can create an instance of itself, and the static method can only be called from within the same package.
I have tried to do this, and was wondering if it will do what I think it will:
I have streamlined the code for your viewing pleasure :-)
package mypackage;
public class MyClass {
      private static final String CHECK_STRING = "wibble";
      private java.util.Vector all = new java.util.Vector();
      private char [] chararray;
      private MyClass() {
            this.chararray = chararray;
            all.add(this);
      protected static boolean create(char [] chararray, String checkString) {
            if (checkString.equals(CHECK_STRING)) {
                  new MyClass(chararray);
                  return true;
            } else {
                  return false;
}Thanks for your help in advance.

Except from having your 'create' method 'protected', it should not have any access-keyword (meaning package access) it is almost as you want it.
static boolean create(char [] chararray, String checkString) will do the trick :-)

Similar Messages

  • Can java have Protected or Private Constructor

    Hi,
    can java have Priavte or protected constructor,
    as we know java have default and public constructor ,
    and in using singleton design patters we can use private & protected constructor,
    so, what is the main logic,
    Regards,
    Prabhat

    Hi,
    Yes, We can declare constructor as private/public/protected also.
    Having only private constructors means that you can't instantiate the class from outside the class (although instances could still be created from within the class - more about this later). However, when you instantiate a class, you must first initialize all superclasses of that class by invoking their constructors. If one of the superclasses has only private constructors declared, we have a problem. We can't invoke the superclass' constructor which means that we can't instantiate our object. Because of this, we've essentially made a class that can't be extended.
    example:
    class TheWorld
    private static TheWorld _instance = null;
    private TheWorld() {}
    public static TheWorld instance()
    if ( _instance == null )
    _instance = new TheWorld();
    return _instance;
    public void spin() {...}
    public class WorldUser
    public static void main(String[] args)
    TheWorld.instance().spin();
    }

  • How to access the private constructor??

    i have a one private constructor in which i define some important variables then how should i access that private constructor?(Is this related to singleton class? if possible give me some example )

    Hi
    you can access to your private constructor through static methods of that class.
    you can create objects of that class using these static method.
    example code
    public class rrr
         public static void main(String[] args)
              a ao=a.getobj(30);
              System.out.println(a.geti(ao));
    class a
         private int i;
         private a(int x)
              i=x;
         static a getobj(int y)
              return new a(y);
         static int geti(a temp)
              return temp.i;
    enjoy .........
    This is my first reply to forum .
    If you found any problem free feel to tell
    Thank you

  • Initiating variables with private constructor fails

    Goodday all,
    At the moment I'm working on a little class that reads the input from the console screen. The class looks like this (I omitted a few unrelevant methods):
    public class SomeClass {
      private static BufferedReader bin = null;
      // private constructor; another method (not shown here) returns an instance
      private SomeClass() {
        bin = new BufferedReader(new InputStreamReader(System.in));//somehow this doesn't work ??????
      //public method
      public final String readLine(String message) {     
              String feedback = "";
              try {
                   if(bin==null) say("variable bin is null"); //bin is indeed null, just don't know why
                   else feedback = bin.readLine();
              catch (IOException e) {
                   e.printStackTrace();
              return feedback;
    }Executing this code will result in output "variable bin is null". When I try debugging it, I see that the variable bin will remain null when the constructor is called.
    Placing the initiation of 'bin' in another method will make things work, but I want to know why it doesn't work in the constructor. It seems as a fair piece of code ;).

    private static BufferedReader bin = null;Why is it static?
    // private constructor; another method (not shown here) returns an instance
    private SomeClass() {
    bin = new BufferedReader(new InputStreamReader(System.in));//somehow this doesn't work ??????
    }'Somehow it fails?' It doesn't even compile!
    Executing this code will result in output "variable bin is null". When I try debugging it, I see that the variable bin will remain null when the constructor is called.Your constructor doesn't even compile, so I find it hard to believe it ever executed.

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

  • Private constructor documented as public by javadoc

    I'm generating document for a class similar to the following:
    public class Example {
    public static final Example TYPE1 = new Example();
    public static final Example TYPE2 = new Example();
    private Example() {
    // private constructor
    When I run the Javadoc tool on this class, it lists the constructor as being public, which it is not! Is this a bug in javadoc, or am I doing something wrong?

    I think I can explain it.
    I would bet you first created the class without any constructor
    and ran Javadoc on it.
    In that case, not only does javac create a public default
    no-arg constructor, but javadoc also documents that constructor,
    even though it's not present in the source file.
    Later, when you added the private constructor, that prevented
    the default constructor from being automatically created.
    This is documented at:
    http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#16823
    BTW, we consider relying on default constructors as poor programming
    practice, as described at:
    http://java.sun.com/j2se/javadoc/writingdoccomments/index.html#defaultconstructors
    -Doug Kramer
    Javadoc team

  • 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.
    ~

  • Getting Private Constructor of a Class

    Hello all,
    Is there any way to get the private constructor as we get the public constructors using Class.getConstructors() ?
    getConstructors() method is not returning the private constructors, but I need the info about the private constructors also....so if it is possible, please let me know...
    Thanks

    tullio0106 wrote:
    I know, however it's also impossible to invoke private methods but, using reflection, You can.That's a complete different thing. If the private method is not static, it is invoked on the current instance.
    Is it also possible to use private constructors in the same way.
    The problem I'm facing is to create a new instance of a class which extends another class and I need to use a private constructor of the superclass (I've no sources of that superclass).First, the Constructor of a class has to invoke a Constructor of a superclass as the first operation (either implicitely invoking an empty constructor or explicitely). There is no way to do any other operation before that. Second, a reflectively fetched Constructor instance always only can create instances of the class it is defined at (using newInstance()). So, yes, you could get access to a private Constructor. With that, you may be able to create a new instance of the class it is defined for. But that's about it.

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

  • Private Constructors and Inheritance

    Hi,
    I have created a class according to the Singleton pattern, with a private constructor to prevent the public creation of class instances. Now I'd like to sub-class the Singleton, but I get errors saying the Singleton constructor is not visible. I guess this is caused by the privateness of the constructor, but I don't know if changing it to protected would ruin the Singleton pattern. Is there a good way to sub-class a Singleton?

    public class SingletonBase {
        private static SingletonBase instance;
        protected SingletonBase() throws InstantiationException {
            synchronized (SingletonBase.class) {
                if (instance != null)
                    throw new InstantiationException("single instance already exists");
                else
                    instance = this;
        public static SingletonBase getInstance() {
            return instance;
    }

  • Why is it that AS3 does not support private constructors as AS2 does?

    Why is it that AS3 does not support private constructors as
    AS2 does?
    Private constructors are standard in most OOP languages (for
    example
    C++ and Java) and were supported in Actionscript 2. However,
    this is
    not the case in AS3 which only allows its constructors to
    have the
    'public' access modifier.
    I have legacy code that I hope to migrate to the AS3
    platform. Some
    key elements of my code rely on design patterns like the
    Singleton
    pattern which in turn depend on private constructors. I could
    refactor
    my code but, ultimately, I would lose the benefits of the
    pattern
    (ie. one and only one instance of the Singleton class).
    I have also used private constructors to simulate enumerated
    types
    much like the enums you would find in Java 5 and up. But I
    can't
    use the same implementation in AS3 without private
    constructors.
    I do not want to resort to mixing legacy code with new AS3
    code to
    keep functionality intact. Are there any possible
    work-arounds for
    this issue?
    If not, are there any lobbying groups I need to know about so
    that
    we can get this feature back?

    http://www.gskinner.com/blog/archives/2006/07/as3_singletons.html

  • Enums - private constructors

    Hi everyone,
    You can define enum's constructors with private and default access.
    Why default ? Is it for programmers' convenience (so they don't have to
    type 'private' manually) ?
    Cheers,
    Adrian

    No , your answer is wrong .
    The enum's constructror cannot ever be used directly , i.e suppose you have enum class E , you cannot ever write in your code :
    E e = new E() (even inside E !!)
    Enums private constructor(s) are alsways invoked automaticaly , from within the enum class itself .
    So the question is again ... why default access constructors are allowed if no one can ever use them ?

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

  • Private constructor in abap OO

    Hi folks,
    I'd like to create a factory method in a class. The factory method returns objects (corresponding to certain keys) of the class by first checking an internal map for the key and then returning the pertaining object if an entry for that key exists or creating a new object (and putting it into the table) if it doesn't.
    Now I wanted to declare the actual constructor <i>private</i>, but found SE80 prohibits changing the accessibility of constructors - there are always public?!
    Is there a way to achieve private accessibility of constructors, what does <i>Instantiation - private</i> on the properties tab of a class mean (as opposed to possibly changing the constructor to private)?
    Great if someone could shed some light onto this.
    Regards,
    Sebastian

    > since you can not call the constructor directly there
    > is no need to declare the constructor as private.
    well, that is almost a philosophical question. I mean in a way I do call the constructor directly: it is called immediately after using the <i>create object</i> command.. but I know what you mean
    > To avoid that an instance can be created from outside
    > the class jsut declare it as
    > class lcl_class definition create private.
    >
    > or if it is global:
    > go to tab properties and set choose private in the
    > instantiation.
    > ...
    > With create private only methods of this class can
    > create an instance of this class...
    That is, only methods of this class can call the constructor (use <i>create object</i>), right?
    This would indeed have the desired effect that creation of this class' objects (somewhere outside the class) was only possible through the factory and not by calling the constructor.
    Thanks, Sebastian

Maybe you are looking for

  • How to use JDBC Connection Pools in a standalone application?

    Hi, there, I have a question about how to use JDBC Connection Pools in an application. I know well about connection pool itself, but I am not quite sure how to keep the pool management object alive all the time to avoid being destroyed by garbage col

  • Business Catalyst will not allow me to add more than 11 items to Web Map? Is there any fix for this?

    Basically I cannot add more than 11 items on to a web app map. If I add more than 11 than the rest of the items appear of the coast of Africa for some reason. I am not sure why this happens but I was wondering if anyone else has had a similar problem

  • Windows 8.1 context after boot

    Having read all the articles on fixing context menus I cannot find a solution for the exact issue I am seeing. When I boot my PC I can right click and select 'open' on my PC. I can then quite happily bring up the context menu on any folder on my driv

  • Lack of print options when using photoshop elements 10 i.e. paper type

    When printing from Photoshop Elements 10 on my MacBook Pro (File Print) there is no where to select paper type or print quality or there doesn't appear to be unlike when selecting print from iphoto. What have I missed? as there must be a way!

  • Filtering parameters in a query

    Hi there, I need some help, I trying to make a query using a filter from the SAP windows of OCRD only for vendor, the search filtering windows present only the CUSTUMES not the VENDORS for example BAPROSA BONO or DIAPA BONO (are two of my custumers i