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

Similar Messages

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

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

  • HT203551 I have an iphone 4, the calls are with Telstra but internet is with dodo, I can recieve emails but not send them?Does anybody know how to remedy this?

    I have an iphone 4, the calls are with telstra but internet is with Dodo.I can recieve emails but not send them?Could anyone please remedy this?

    Welcome to the Apple Community.
    i assume the email account is your iCloud email account. have you tried turning off settings > iCloud > mail, restarting the phone and then re-enabling mail again.

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

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

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

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

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

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

  • Constructor can throw exception or Not ?

    Anybody please tell me if the constructor throws an exception or not ?
    Please reply soon
    Thanks
    Amitindia

    A constructor can throw an Exception. However I
    would suggest throwing the generic Throwable, Error,
    Exception or RuntimeException rather than a specific
    exception is bad practice and you should choose an
    appropirate exception to throw.All depends on wich kind of exception you are throwing,checked or unchecked. It's an even worse form to throw a RE, Error, or Throwable when you are throwing in fact a checked exception.
    Nevertheless, I do agree, you must always strive to not throw exceptions, of any kind, in your construtor code. Construtors should be simple and reliable. Unles you have a very compelling reason to not do it, try to isolate the risky parts of the code where they are called ofter object construction or class loading.
    May the code be with you.

  • Airport Express can only extend network, not create new one. Why?

    I am sharing a flat with some friends. The shared broadband router is placed in the living room. To strengthen the signal and make it easier for me to manage, I bought an Airport Express, connected it to the shared router with an ethernet cable and set up a wireless network of my own in my room. It was working fine, until recently we renewed our broadband contract. The router had been replaced by a new one (I don't know why) and the network configration had been changed. Since then I was not able to use my own network. In the Airport Utility display, the light of Airport Express is green, but the light of Internet is yellow, and the status is disconnected. I tried to change various other configuration on the Airport Express, and all in vain. Until I switched the network mode from 'Create a new wireless network' to 'Extend a wireless network', the Internet connection was finally back online. But this merely extends the existing network and not what I want. Why this happens? Why my Airport Express can only extend a network, not create one?

    Here is the situation on my Airport Express.
    If I choose to extend the existing wireless network, the Airport Utility shows like this:
    If I set up a wireless network of my own, what I get in the Airport Utility is this:
    See my problems here? The Airport Express does not show anything in amble, but the Internet complains that there is no connection.
    This problem did not occur before the broadband was renewed and the rounter was replaced.

  • HT204380 When I contact someone with FaceTime, they can see me but not hear me.  I can see and hear them.  What am I doing wrong?

    When I contact someone on FaceTime, they can see me but not hear me.  I can see and hear them.  No one has ever been able to hear me.  What am I doing wrong?

    Using FaceTime http://support.apple.com/kb/ht4319
    Troubleshooting FaceTime http://support.apple.com/kb/TS3367
    The Complete Guide to FaceTime: Set-up, Use, and Troubleshooting Problems
    http://tinyurl.com/32drz3d
    I saw one post where a user said dust got inside the small microphone hole. Using a vacuum cleaner removed the dust and restored the audio.
     Cheers, Tom

  • 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

  • JDev 11 - Date problem in executeWithParams form who rans fine in Jdev 10

    Hello everybody, Here is my case : I have a viewObject, here is its SQL code : select * from   select req.*, ROW_NUMBER() OVER(ORDER BY 1) num   from     select distinct rvmage.mage_seq, mpr.nom||' '||mpr.prenom as medecin, mpr.nom, mpr.prenom, rvmag

  • Repository Creation to SQL Server

    I am trying to evaluate the ODI software by using a SQL Server database for the repository. I am getting an error when I try to test the connection which does not make sense since it appears I am following the syntax for a JDBC connection. Here are t

  • Test Framework

    Hey guys, sorry if im posting in the wrong place, Just wondering if anyone knows of good testing tools or frameworks specifically to handle session initiation protocol (sip) servers and Instant messaging applications. Sorry for the very open ended qu

  • Some question about flex and facebook, and saving server work!

    Hi guys im starting to develop facebook application and im not surre what is the better way to connect my app to facebook. first option is to pull all the data from facebook through PHP and then send it to the app. or getting the data directly to my

  • Am I eligible for Adobe Revel Premium?

    I had purchased an upgrade in Photoshop.com.  Am I eligible for Revel Premium? Not all of my pictures have transferred.