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();
}
Similar Messages
-
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
-
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 -
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 -
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
SumitKaranjit 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()
} -
i have deleted my private folder and do not have enough space to reinstall my operating system. How can i transfer files from my hard drive to an USB drive to free up space when the operating system isn't working. or do i need to erase disk through disk utilities without erasing data (but will it delete my programs such as photoshop, office, creative suite?
Connect the computer to another Mac and put it in FireWire Target Disk mode, or use the Disk Utility to clone the drive or image specific folders with the USB drive as the target. After you've copied off everything you want, you'll likely need to erase the drive and reinstall the applications.
(69695) -
I have protected pdf files. You can not copy things, but it is allowed to print. In the menu of the pdf it says you are allowed to print. I already printed lots of times the document. But today there is an error "The printer is not admittet to print these pdf". Its new. Theres no problem with the printer. I can print word documents, internet pages etc. But today I can not print anymore my pdf document, although printing is allowed and only copying is forbidden.
How to solve the problem with the pdf?
Thank you.Hi Hans,
There seems to be other restrictions in the document that's not allowing it to print.
Would it be possible to share the document with me so that I can have a look?
Regards,
Rave -
How can i have a refrence of a java class object instance in my c++ project
Hi!
How can i have a refrence of a java class object instance in my c++ project. Is there a way?hahaxia wrote:
The second question is the big one. The first question is half of the problem of "c++ to java" invocation and access. But the other half which is "java to c++ " invocation and access is still not solved. jni only provide the "java to c++ " DLL invocation Wrong,
Using JNI your java classes can have methods implemented in C/C++.
Using JNI you can call java classes.
There is no other possible interaction between C++ and java, so it does it all. -
How can I have a #defined in Java?
How can I have a #defined in Java that
works like C/C++?
Edited by: thunderball1234 on Mar 25, 2009 7:55 AMBigDaddyLoveHandles wrote:
I just threw up in my mouth a little. Why do you want to preprocess Java files?I have some code that works with primitive arrays and I want to use that code for byte, char, double, float and long. I first wrote this as a file to be processed by cpp, I then changed to use perl and now I use XSLT.
What is interesting to me is that the perl version was easiest to write and easiest to maintain. The XSLT version is bloody difficult to understand.
Edited by: sabre150 on Mar 25, 2009 4:03 PM -
Cmp-field of type 'java.lang.Long' does not have a no-arg constructor
Hi,
I am a newer of Oracle9i JDeveloper and I am learning it by "Oracle9i JDeveloper Reviewers Guide". I did the sample as the guideline in "Oracle9i JDeveloper Reviewers Guide". But when I tried to run the sample I made, the error : "cmp-field of type 'java.lang.Long' does not have a no-arg constructor which is needed for properties/fields based mapping" was appeared.
Any one know how to correct it?
Thanks in advance.
Best Regards,
Double
Auto-deploying file:/E:/JDev9i/jdev/Workspace2/J2EE/classes/ (No previous deployment found)...
Error compiling E:\JDev9i\jdev\Workspace2\J2EE\classes: cmp-field of type 'java.lang.Long' does not have a no-arg constructor which is needed for properties/fields based mapping
Oracle9iAS (9.0.3.0.0) Containers for J2EE initializedI'm getting the same thing. The message doesn't indicate which of the four beans I have that use type Long is encountering this. I suspect that since it says 'constructor' it is one of the two which uses an Long for a primary key.
Yet another OC4J bug,
Michael A. Moran -
Unfortunately this discussion forum has changed and become confusing indeed. It wanted me to put my entire question in a Subject box which wasn't labeled as such, and I find this strange. Especially since now it tells me to repeat my question in this box, so here goes.
Has anyone here used a program called 'Cookie' that is supposed to protect our private information from sites which could retrieve it when we surf the Net. If so, do you consider the program worth buying?If you are referring to Cookie from SweetP Productions, I have tried it and not found it to work reliably, so I cannot recommend it. I've had the best results with the same company's free Safari Cookies, though it's not perfect (none of the cookie managers are, unfortunately):
http://www.macupdate.com/app/mac/31018/safari-cookies
Regards. -
How do I create a folder for private documents which can be password protected?
how do I create a folder which can be password protected please?
You can do this by creating a protected disk image.
Instructions here http://www.macworld.com/article/154559/2010/10/password_protect_folders.html
Or you can buy and use software like this one: http://www.apimac.com/mac/secretfolder/
The disk image option is free and easy to do. -
Defining a Private Constructor in private section of the class?
In the exercises of ABAP OOPs book, I have the found following question.
Q. A private instance constructor (instantiation only by the class itself) can be defined in the private section.
True or False
The answer provided in the book is "True". But actually, its not possible to define a constructor in a private or protected section, regardless of the constructor visibility.
Can anyone help me in this question?from the ABAP help:
The statement METHODS constructor for the declaration of the instance constructor of a class declared with the adition CREATE PRIVATE, can not only be listed in the public, but also in the protected or private visible area. This allows the use of components, which have been declared there, in the interface of the constructor.
the problem might be your SAP system version. I have verified this on Netweaver 7.00.
best regards,
J.N.N -
Help : java.security.UnrecoverableKeyException: excess private key
Hi,
I require help for the exception "java.security.UnrecoverableKeyException: excess private key"
When i am trying to generate digital signature using PKCS7 format using bouncyCastle API, it gives the "java.security.UnrecoverableKeyException: excess private key" exception.
The full stack trace is as follows
------------------------------------------------------------------------java.security.UnrecoverableKeyException: excess private key
at sun.security.provider.KeyProtector.recover(KeyProtector.java:311)
at sun.security.provider.JavaKeyStore.engineGetKey(JavaKeyStore.java:120)
at java.security.KeyStore.getKey(KeyStore.java:289)
at com.security.Security.generatePKCS7Signature(Security.java:122)
at com.ibm._jsp._SendSecureDetail._jspService(_SendSecureDetail.java:2282)
at com.ibm.ws.jsp.runtime.HttpJspBase.service(HttpJspBase.java:93)
I had tested the program under following scenarios...
The Java Program for generating the digital signature independently worked successfully(without any change in policy files or java.security file) I have tested this independently on Sun's JDK 1.4, 1.6
For IBM JDK 1.4 on Windows machine for WAS(Webshere Application Server) 6.0, The Program for generating the digital signature using PKCS7 works fine, but it required IBM Policy files(local_policy.jar, US_export_policy.jar) and updation in java.security file
But the problem occurs in Solaris 5.10, WAS 6.0 where Sun JDK 1.4.2_6 is used.
I copied the unlimited strength policy files for JDK 1.4.2 from Sun's site(because the WAS 6.0 is running on Sun's JDK intead of IBM JDK)...
I changed the java.security file as follows(only changed content)
security.provider.1=sun.security.provider.Sun
security.provider.2=com.ibm.security.jgss.IBMJGSSProvider
security.provider.3=com.ibm.crypto.fips.provider.IBMJCEFIPS
security.provider.4=com.ibm.crypto.provider.IBMJCE
security.provider.5=com.ibm.jsse2.IBMJSSEProvider2
security.provider.6=com.ibm.jsse.IBMJSSEProvider
security.provider.7=com.ibm.security.cert.IBMCertPath
security.provider.8=com.ibm.security.cmskeystore.CMSProvider
I have used PKCS12(PFX) file for digital signature
which is same for all environment(i have described as above)
I copied the PFX file from windows to solaris using WinSCP in binary format so the content of certificate won't get currupted.
I can not change the certificate because it's given by the company and which is working in other enviroments absolutely fine(just i have described above)
I have gone though the "http://forums.sun.com/thread.jspa?threadID=408066" and other URLs too. but none of them helped...
So what could be the problem for such exception?????
I am on this issue since last one month...
I know very little about security.
Thanks in advance
PLEASE HELP ME(URGENT)
Edited by: user10935179 on Sep 27, 2010 2:47 AM
Edited by: user10935179 on Sep 27, 2010 2:54 AMuser10935179 wrote:
The Java Program for generating the digital signature independently worked successfully(without any change in policy files or java.security file) If the program was working fine without changing the java.security policy file, why have you changed it to put the IBM Providers ahead of the SunRsaSign provider?
While I cannot be sure (because I don't have an IBM provider to test this), the error is more than likely related to the fact that the IBM Provider implementations for handling RSA keys internally are different from the SunRsaSign provider. Since you've now forced the IBM provider ahead of the original Sun provider, you're probably running into interpretation issues of the encoded objects inside the keystore.
Change your java.security policy back to the default order, and put your IBM Providers at the end of the original list and run your application to see what happens.
Arshad Noor
StrongAuth, Inc. -
Can you have code run in a terminal and applet?
For example in my program in Main we enter the data for menu and amount of the exchange but the result is displayed in an applet.
works great in the terminal window.
but when using an applet it will not work.
import java.awt.*;
import java.applet.*;
import javax.swing.* ;
import TerminalIO.*;
public class MetricConversionMain {
final static String CRLF = "\n" ;
static String msgOut ;
public static void main ( String[] args ) {
int valid = 0;
int choose = 0;
double numUnits = 0.0;
double convertedUnits = 0.0;
// title, class, author and version info to
KeyboardReader entries = new KeyboardReader(); //object for keyboard entry
while (valid != 1) {
// menu for conversion selection 1 thru 4
System.out.println("\n\t\t1 \tFor inches to centimeters");
System.out.println("\t\t2 \tFor quarts to liters");
System.out.println("\t\t3 \tFor pounds to kilograms");
System.out.println("\t\t4 \tFor miles to Kilometer");
choose = // GW corrected my code to the present prior I was choose = choose.readInt etc etc
entries.readInt("\n\t\tPlease choose one of the following menu items to convert: ");
if (choose == 1 || choose == 2 || choose == 3 || choose ==4 ) {
valid = 1 ;
else {
System.out.println("Invalid Selection.") ;
switch (choose) {
case 1 : System.out.println("Converting inches to centimeters... ") ; break ;
case 2 : System.out.println("Converting quarts to liters... ") ; break ;
case 3 : System.out.println("Converting pounds to kilograms... ") ; break ;
case 4 : System.out.println("Converting miles to kilometers... ") ; break ;
} // Error checking, reiterates the user's current choice prior to next question
System.out.println();
KeyboardReader useEntry = new KeyboardReader(); //object for keyboard entry
numUnits =
useEntry.readDouble("\n\t\tNow please enter the amount you wish to convert: ");
System.out.println ("\t\tThe conversion comes to " + numUnits);
//KeyEntry equal = new KeyEntry();
//equal.setNumUnits
//(useEntry.readDouble("\n\t\tNow please enter the amount you wish to convert: "));
//System.out.println("\t\tThe conversion comes to " + getnumUnits());
switch (choose) {
case 1 : Inch fromInch = new Inch(numUnits); break ;}
case 2 : Quart fromQuart = new Quart(numUnits) ; break ;
/* case 3 : Pound fromPound = new Pound( numUnits) ; break ;
case 4 : Mile fromMile = new Mile(numUnits) ; break ;
} // Switch statement that performs the correct conversion based on the user's input*/
// Instantiate US Standard Objects
/* Inch fromInch = new Inch(1) ;
Foot fromFoot = new Foot(1) ;
Yard fromYard = new Yard(1) ;
Mile fromMile = new Mile(1) ;
Ounce fromOunce = new Ounce(1) ;
Quart fromQuart = new Quart(1) ;
Gallon fromGallon = new Gallon(1) ;
Pound fromPound = new Pound(1) ;
// Instantiate Metric Objects
Centimeter fromCentimeter = new Centimeter(1) ;
Meter fromMeter = new Meter(1) ;
Kilometer fromKilometer = new Kilometer(1) ;
Gram fromGram = new Gram(1) ;
Liter fromLiter = new Liter(1) ;
Kilogram fromKilogram = new Kilogram(1) ;
LitGal fromLitGal = new LitGal(1) ; */
} // main
} // class MetricConversionMainsupper classpublic class SuperConverter {
* This class is the super class for a series of
* subclasses that perform conversion from metric to
* imperial or vice versa.
protected double numUnits ;
protected double convertedUnits ;
protected double factor ;
// Constructor
public SuperConverter ( double argNumUnits, double argFactor ) {
numUnits = argNumUnits ;
factor = argFactor ;
convertedUnits = numUnits * factor ; //convert() ;
} // Constructor
protected double getnumUnits() {
return numUnits ;
protected void setnumUnits ( double argNumUnits ) {
numUnits = argNumUnits ;
protected double convert () {
this.convertedUnits = numUnits * factor ;
return convertedUnits ;
public double getconvertedUnits() {
this.convertedUnits = convert() ;
return convertedUnits ;
} // end SuperConverter Classsubclass that works[public class Inch extends SuperConverter {
public Inch (double argNumUnits)
super ( argNumUnits, 0.914 ) ;
System.out.print (" ") ;
if (argNumUnits > 1)
System.out.println(argNumUnits + " inches = " + convertedUnits + " centimeters") ;
else
System.out.println(argNumUnits + " inch = " + convertedUnits + " centimeters") ;
/code]
The code I want to use with the applet is import java.awt.*;
import java.applet.*;
import javax.swing.* ;
public class Inch extends SuperConverter {
final static String CRLF = "\n" ;
static String msgOut ;
public Inch (double argNumUnits)
super ( argNumUnits, 2.54 ) ;
System.out.print (" ") ;
if (argNumUnits > 1)
{ msgOut = " Metric Conversion Chart" + CRLF + CRLF;
msgOut += " US Standard to Metric" + CRLF ;
msgOut += " -------------------------------------------------" + " " + CRLF ;
msgOut = argNumUnits + " inches = " + convertedUnits + " centimeters" ;
else
{ msgOut = " Metric Conversion Chart" + CRLF + CRLF;
msgOut += " US Standard to Metric" + CRLF ;
msgOut += " -------------------------------------------------" + " " + CRLF ;
msgOut += argNumUnits + " inch = " + convertedUnits + " centimeters" + CRLF + CRLF + CRLF ;
} JOptionPane.showMessageDialog ( null, msgOut ) ;
}The issue I have is the applet/window appears behind the terminal window. below is the code that is use for the window. I want to have the window appear infront of the terminal window.import java.awt.*;
import java.applet.*;
import javax.swing.* ;
public class Pound extends SuperConverter {
final static String CRLF = "\n" ;
static String msgOut ;
public Pound (double argNumUnits)
super ( argNumUnits, 0.454 ) ;
System.out.print (" ") ;
if (argNumUnits > 1)
{ msgOut = " Metric Conversion Chart" + CRLF + CRLF;
msgOut += " Metric to US Standard" + CRLF ;
msgOut += " -------------------------------------------------" + " " + CRLF ;
msgOut += argNumUnits + " pounds = " + convertedUnits + " kilograms" + CRLF + CRLF + CRLF ;
else
{ msgOut = " Metric Conversion Chart" + CRLF + CRLF;
msgOut += " Metric to US Standard" + CRLF ;
msgOut += " -------------------------------------------------" + " " + CRLF ;
msgOut += argNumUnits + " pound = " + convertedUnits + " kilograms" + CRLF + CRLF + CRLF ;
} JOptionPane.showMessageDialog ( null, msgOut ) ;
}
Maybe you are looking for
-
Dear All, In my scenario am using one raw material for producing one finished goods. In B1 we can track the inventry for raw material and finished goods but how can i track the inventry details for Work in progress items. now i can able to t
-
New desktop software synching problem
Just tried to synch my Blackberry to my Outlook. Got a message that Intellisynch was no lionger being used, there was a new program and I had to reconfigure the settings. After doing that the program went through the preliminary steps and has now be
-
If i update itunes will i lose my apps and contacts and the other contents?
if i update itunes will i lose my apps and contacts and the other contents?
-
TIFF vs PSD (16 bit) pros cons?
Hi everyone, I am trying to streamline my Aperture Photoshop workflow and I was wondering what are the real differences and pros and cons to using TIFF or PSD in 16 bit? What would I gain/loose by using PSD or TIFF when editing in PS and saving? Than
-
Just upgraded to OS 6.0. Deleting unwanted mailboxes > asked to update Email Set Application > did so > BB dies with message...App Error 606, Reset. What to do?