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

Similar Messages

  • Creating an instance of a class with no default constructor

    Hello gurus,
    I wrote my own serialization and RMI protocol for both C++ and Java that follows closely what the default Java version does. I'm trying to recreate an object on the Java side that was sent over the wire. The first step is to create an instance of the class. How do I create an instance of a class that has no constructor (i.e. the only instances are static, created by the class itself and returned by static methods) or one that has no default constructor (like Integer)? The Java serialization seems to support it but the reflection API doesn't seem to have any support for this (i.e. Class::newInstance() and Constructor::newInstance()). It seems that through the standard API you can only create an object via one of its constructors. There must be a "hidden" method somewhere that allows the Java serialization to create an object without calling a constructor - where is it?
    Dominique

    There must be a "hidden" method
    somewhere that allows the Java serialization to create
    an object without calling a constructor - where is
    it?You are correct, the way in which the Serialization creates Objects is "hidden" deep within the runtime.
    If it were not hidden, you would be able to find it, and use it to violate the integrity of the VM.

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

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

  • How to instantiate class via reflection

    Hi, I want to generically instatiate classes, but obviously Class.newInstance only works if the class has a public no args constructor. Is there any way to instantiate classes without such a constructor via reflection? It would be sufficient for me if I could use a private no args constructor.
    I already tried the following:
    Class clazz = Class.forName( "classname" );
    Constructor constructor =
    clazz.getDeclaredConstructor( new Class[] { } );
    constructor.setAccessible( true );
    object = constructor.newInstance( new Object[] {} );
    But it, too, yielded to an IllegalAccessException.

    Class clazz = Class.forName( "classname" );
    Constructor constructor =
    clazz.getDeclaredConstructor( new Class[] { } );
    constructor.setAccessible( true );
    object = constructor.newInstance( new Object[] {} );
    But it, too, yielded to an IllegalAccessException.constructor.setAccessible( true );
    is the call that generates the IllegalAccessException. Your code must be allowed to supress access checks. This is always the case if you don't have a security manager, otherwise the security manger's checkPermission method is called with an ReflectPermission("supressAccessChecks") argument.
    Either that or the getDeclaredConstructor throws the exception, in that case your code must be allowed to "check member access".
    Hope it helped,
    Daniel

  • Anonymous classes and non-default constructors

    I've got a class with only one constructor and that takes an argument. In another class, I want to have an anonymous class that extends this class with something like:
    new MyClassWithoutDefaultConstructor(myConstuctorArg) {...}
    However, I get a "The constructor MyClassWithoutDefaultConstructor() is undefined".
    As a workaround I can create a local class (not anonymous) that extends MyClassWithoutDefaultConstructor and then includes a default constructor which passes my arg to the super constructor. But this is rather messy.
    Am I missing something?

    The following works fine for me (prints 5):
    public abstract class Test
        private final int parameter;
        public Test(int parameter)
            this.parameter=parameter;
        public int getParameter()
            return parameter;
        public abstract int getSomething();
        public static void main(String[] args)
            Test test=new Test(3)
                public int getSomething()
                    return getParameter()+2;
            System.out.println(test.getSomething());
    }You say your anonymous class is in a different class to the one it extends - what is the access modifier on the constuctor you are calling in the base class? Is the constructor visible from the class containing the anonymous class? Can you post a concise example that produces the compiler error that you are getting?

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

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

  • Need to instantiate a class with the contents of a string variable

    I have:
    String temp = "hello";
    and I want to instantiate a class with the contents of the variable temp. So what I want is:
    Class hello = new Class();
    Does anybody know how to do this?

    I'm getting kind of confused with decifering what
    people are writing. I'm not real sure what the Java
    syntax is and what I should be modifying for my code.
    Basically, I have created a class called Artist. I
    want to parse through a text file and when I see a
    header field called "artist", my program will
    instantiate the artist class with the next String
    token. For example, if my text file reads:
    --artist:Daniel
    I want to create an Artist object with the name
    Daniel. Ideally I could just use the code:
    --Artist Daniel = new Artist();I cannot use this syntax because I don't know that "Daniel" is going to follow "artist" in the text file. It could be a different name or String
    >
    But the way I'm going about it right now is to store
    "Daniel" in a variable called temp by:
    --//"in" is an instantiation of StreamTokenizer
    --String temp = in.sval;    
    Right now I have the Artist class set up so there is
    just a default constructor.

  • 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 no constructors

    The class javax.microedition.rms .RecordStore does not have a constructor. Why?
    Please note that I am not asking how to produce an instance of a RecordStore, I have read the documentation and am aware of the static openRecordStore method.
    Paul Hide

    javax.microedition.rms.RecordStore has no public or protected constructor so you can't extend it.
    If a private constructor is defined in a class then it is not exposed in documentation (usually), but at the other hand if you have not defined any constructor then non-argument public constructor is shown in the documentation.
    So it seems that javax.microedition.rms.RecordStore has private constructor.
    So you can't extend it.
    Following two type of classes are non-extendable:
    - Whose all constructors are made private. E.g. java.lang.Runtime, java.lang.System.
    - Final class (just final keyworkd is added in access specifiers). E.g. java.lang.String
    Following two type of classes are non-instantiable:
    - Whose all constructors are made private. These can be instantiated inside the class. E.g. java.lang.Runtime, java.lang.System
    - Abstract class (just abstract keyword is added in access specifiers). E.g. java.io.OutputStream
    Regards,
    Humayun.

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

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

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

Maybe you are looking for