Use of a private constructor - java

I'm a begginer programmer for Android and I found some code over the internet and I couldn't get what this "Class not meant to be instantiated" means?! Also what's the use of it. I would be very happy if somebody could help here.
public class Settings
{
//some code
private Settings() {} // Class not meant to be instantiated
//some code
}

The constructor is private so only the class itself can create instances. There are several reasons for doing this. A couple off the top of my head...
The class is a "utility" class that only contains static methods and so instantiating it would make no sense. As the class is commented "Class not meant to be instantiated" I guess this is the most likely reason.
The class itself controls its own lifecycle and provides methods for creating instances. For example if the class is a lazy singleton it might provide a method that creates an instance when first called and return this instance on subsequent calls.

It is a private constructor. This means that outside classes cannot create new instances using the default constructor.
A little more info
All Objects in Java have a default constructor:
public MyObject() {}
That is how you can have this class:
public class MyObject{}
and still be able to call:
MyObject mObj = new MyObject();
Private Constructors
Sometimes a developer may not want this default constructor to be visible. Adding any other constructor will nullify this constructor. This can either be a declared constructor with empty parameters (with any of the visibility modifiers) or it can be a different constructor all together.
In the case above, it is likely that one of the following models is followed:
The Settings object is instantiated within the Settings class, and is where all the code is run (a common model for Java - where such a class would also contain a static main(String[] args) method).
The Settings object has other, public constructors.
The Settings object is a Singleton, whereby one static instance of the Settings Object is provided to Objects through an accessor method. For example:
public class MyObject {
private static MyObject instance;
private MyObject(){}//overrides the default constructor
public static MyObject sharedMyObject() {
if (instance == null)
instance = new MyObject();//calls the private constructor
return instance;
}
}

This inner construct
private Settings() {}
is a constructor for Settings instances. Since it is private, nobody can access it (outside of the class itself) and therefore no instances can be created.

The constructor is private so its not meant to be called by anything outside of the class

It's not a nested class, it's a constructor. A private constructor means that you can't construct instances of this class from outside, like this:
Settings s = new Settings(); //Compilation error! :(
Now, if a class can't be instantiated, what could it be for? The most likely reason for this is that the class would return instances of itself from a static method, probably as a singleton. The settings are normally global to the program, so a singleton pattern really fits here. So there would be a static method that goes kind of like this
static private TheOnlySettings = null;
static public getSettings()
{
if(TheOnlySettings == null)
TheOnlySettings = new Settings(); //Legal, since it's inside the Settings class
return TheOnlySettings;
}
See if that's indeed the case.

As other have mentioned, a class having private constructors cannot be instantiated from outside the class. A static method can be used in this case.
class Demo
{
private Demo()
{
}
static void createObjects()
{
Demo o = new Demo();
}
}
class Test
{
public static void main (String ...ar)
{
Demo.createObjects();
}
}

We can have private constructor . Below program depicts the use of private constructor with a static function
class PrivateConstructor {
private:
PrivateConstructor(){
cout << "constructor called" << endl;
}
public:
static void display() {
PrivateConstructor();
}
};
int main() {
PrivateConstructor::display();
}

Related

Why wouldn't you make a nested class static?

If I have class with a nested class, why wouldn't you want it to be static? Is there even a way for two instances of the same class to have different nested classes?
For example:
class MyClass {
public static class myInnerClass {
}
}
why wouldn't you want it to be static
Because I want it to access instance data of a parent object.
Is there even a way for two instances of the same class to have different nested classes?
What do you mean by have? Declared? A class has only one declaration where you list all nested classes. So, in this case the answer is no.
Take for example a Comparator or Runnable (multi-threading) implementations. This is a classic example when you need an extra class that has access to the current instance's fields and methods but is of no use outside of that class. However, static classes could be useful outside the enclosing type, too.
public class EnclosingType
{
private static final class StaticRunnableImplementation implements Runnable
{
private final EnclosingType instance;
public StaticRunnableImplementation(EnclosingType instance)
{
this.instance = instance;
}
#Override
public void run()
{
instance.getSomething();
//getSomething() leads to compile error
}
}
public class NonStaticRunnableImplementation implements Runnable
{
#Override
public void run()
{
doStuff();
}
}
public int getSomething()
{
return 42;
}
public synchronized void doStuff()
{
;
}
public void doSomething()
{
Thread t1 = new Thread(new StaticRunnableImplementation(this));
Thread t2 = new Thread(new NonStaticRunnableImplementation());
t1.start();
t2.start();
}
}
The access to the non-static methods and fields of current instance of the enclosing type, wouldn't be possible if the nested classes would be declared static.
I don't know if I understand your question correctly, but the difference between a static inner class to a non-static is that the second needs a reference from the parent class to be created.
It's preferable to create static class, because of "hidden ciclic references" that can be created. For example, it's normal in GUI developing you do something like
public class View {
private Table table;
...
private void addListeners() {
this.table.addListener(new TableSelectionListener());
}
privte class TableSelectionListener implements Table.SelectionListener {
#Overrides
public void selected(SelectionEvent evt) { /* do stuff.*/ }
}
}
Lots of programmers don't realize, but you now have a circular reference between View and Table, because SelectionListener, being non static, saves a reference to its parent. So
View -> Table -> TableSelectionListener --> View
If you declare TableSelectionListener static it will only need the "namespace" from view to be created, but besides that, it will not save a reference to any View unless you save it on a field. But then, you will return to the first problem :P
Hope that helps :)
A non-static nested class is associated and has access to the members of an enclosing class instance:
Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private.
If you implement a Listener of some kind, for example, you usually want to call a method on the outer class when you receive the event. In that case, an inner class is simpler than a nested class with an explicit reference to the outer class instance.
That's often used in GUI components. For example (using an API which doesn't actually exist):
public class CircleView extends View {
private final Circle circle = new Circle();
private final Button button = new Button();
public CircleView() {
circle.setColor(Color.RED);
button.addClickListener(new MyClickListener());
}
private toggleColor() {
circle.setColor(circle.getColor() == Color.RED ? Color.BLUE : Color.RED);
}
private class MyClickListener implements ClickListener() {
#Override
public void onClick() {
// Only possible because of the implicit reference:
toggleColor();
}
}
}
A non-static nested class allows the following in an implicit/magical way:
class MyClass {
public static class MyInnerClass {
final MyClass myClass_this;
public MyInnerClass(MyClass parent) {
// Nested class instance has/keeps access to "parent" object.
// In a nested non-static class the "parent" is -guaranteed- to be
// non-null as the nested class can only be created with
// an instance of the containing class.
myClass_this = parent;
}
public Foo bar() {
// Use myClass_this
// Would be available as MyClass.this or implicit resolution in a
// a nested non-static class.
}
}
}
The rules for scope access are also a bit different but the above should show when it might be useful/desirable. In both cases there is only one type for the inner class (MyClass$MyInnerClass), although there can be many instances.
Wether or not this is a "good" thing to have such non-static nested type behavior is debatable, but it is provided in Java.
However, one case where this "non-static" behavior is extremely useful in Java is with anonymous classes (e.g. event handlers or callbacks) which behave as non-static nested classes; while a "different" construct the same mechanism allows accessing methods defined in the enclosing type. Moving the anonymous classes to non-static nested classes can thus merely be viewed as an extension of this common idiom that also allows exposing the nominative type.
(C# has no notion of a "non-static" nested class, but it is easy to emulate it as per above - although I would argue it's usually better to pass a more-refined interface. In addition, other constructs such as closures minimize the need/use even more.)

Hiding the visibility of a class to other classes

Basically I have a class which an instance of is created via a Singleton class. The class should never been instantiated via any other means than the singleton class. My question is can the class be effectively 'not seen' by other classes, apart from Singleton.
I know inner classes and different pacakages etc would help, but I'm curious to see if anyone has a nice solution to this.
Thanks for replies
Just refactor class itself as singleton. Private constructor and etc.
An easy and efficient way to do Singleton with an Enum:
public enum Singleton {
INSTANCE;
public void execute (String arg) {
//... perform operation here ...
}
}
In a sample scenario, using your API, do I need to declare?:
ToBeInvisibleClass instance = TheSingleton.getThatInvisibleInstnace();
If the answer is Yes, then the answer to your question is No since I need to declare a variable and for that I need the type to visible. If the answer is No, then using inner/nested class seems to be a proper approach or making the class itself the singleton.
Java has no "friend" concept like C++
You mentioned nested classes (real inner classes will not work because they need the outer) and packages.
Other approaches to protected other classes but one from creating an instance are not known to me.
But in general there is no reason to build a singleton by an helper class.
You could build singleton using enums or static final vars
What is the best approach for using an Enum as a singleton in Java?
public enum Elvis implements HasAge {
INSTANCE;
private int age;
#Override
public int getAge() {
return age;
}
}
class X {
public static final X instance = new X ();
private X () {
}
...
}
To assure that instantiation only occurs through your class method, you can do the following:
Make the default constructor private
Save your singleton instance in a private method
Use a public static method to provide the instance to the clients:
In this site there's a nice example:
public class MySingleton {
private static MySingleton _instance = new MySingleton();
private MySingleton() {
// construct object . . .
}
public static MySingleton getInstance() {
return _instance;
}

How can I statically instantiate a member that depends on an instance method?

There is base class A which has a method to load a data source.
Various classes are derived from A including derived class B.
Now I need to have a static member variable in class B e.g. mStaticOfB that is instantiated only once for ALL instances of class B to use.
The caveat here is that to instantiate the static mStaticOfB I need to use the data source inherited by base class A.But I need an instance of an object to get that and I don't have it at that point.
How can I get arround this problem? Is there a good/standard way to handle this?The only idea that I came up (and trying not to use) is to make
class B a singleton.
What Nishant said, except threadsafe:
private static FieldType mStaticOfB;
...
public B(..) {
super();
synchronized(B.class) {
if (mStaticOfB == null) {
//code to set mStaticOfB
}
}
}
you could just have class B with unitialized static mStaticOfB, that gets initialized iff mStaticOfB the time when the first time the constructor is called.
private static FieldType mStaticOfB;
...
public B(..){
if(mStaticOfB==null){
//code to set mStaticOfB
}
}

Constructor's Private scope

Given this code snippet, could you explain why it woks?
The thing is that the class constructor is marked private, so should not it prevent us to call it with new operator?
public class Alpha {
protected Alpha() {}
}
class SubAlpha extends Alpha {
private SubAlpha() {System.out.println("ok");}
public static void main(String args[]) {
new SubAlpha();
}
}
It all works because the static method is part of the class and it can see all private fields and methods, right? Outside this "new" initialization would never work?
The only private constructor in your question is SubAlpha, which SubAlpha itself is calling. There's no issue, a class can call its own private methods. The Alpha constructor is protected, so SubAlpha has access to it.
Edit: Re your edit: Yes, exactly. A separate class (whether a subclass or not) would not have access to SubAlpha's private constructor and could not successfully construct a new SubAlpha().
Example 1:
public class Beta
{
public static final void main(String[] args)
{
new SubAlpha();
// ^--- Fails with a "SubAlpha() has private access in SubAlpha"
// compilation error
}
}
Example 2:
public class SubSubAlpha extends SubAlpha
{
private subsubAlpha()
{
// ^== Fails with a "SubAlpha() has private access in SubAlpha"
// compilation error because of the implicit call to super()
}
}
This is, of course, constructor-specific, since scope is always member-specific. If a class has a different constructor with a different signature and a less restrictive scope, then a class using it (including a subclass) can use that other constructor signature. (In the case of a subclass, that would require an explicit call to super(args);.)
The code works as the main method is also in the same class. You may not be able to initialize SubAplha from a different class.

Why are you not able to declare a class as static in Java?

Why are you not able to declare a class as static in Java?
Only nested classes can be static. By doing so you can use the nested class without having an instance of the outer class.
class OuterClass {
public static class StaticNestedClass {
}
public class InnerClass {
}
public InnerClass getAnInnerClass() {
return new InnerClass();
}
//This method doesn't work
public static InnerClass getAnInnerClassStatically() {
return new InnerClass();
}
}
class OtherClass {
//Use of a static nested class:
private OuterClass.StaticNestedClass staticNestedClass = new OuterClass.StaticNestedClass();
//Doesn't work
private OuterClass.InnerClass innerClass = new OuterClass.InnerClass();
//Use of an inner class:
private OuterClass outerclass= new OuterClass();
private OuterClass.InnerClass innerClass2 = outerclass.getAnInnerClass();
private OuterClass.InnerClass innerClass3 = outerclass.new InnerClass();
}
Sources :
Oracle tutorial on nested classes
On the same topic :
Java: Static vs non static inner class
Java inner class and static nested class
Top level classes are static by default. Inner classes are non-static by default. You can change the default for inner classes by explicitly marking them static. Top level classes, by virtue of being top-level, cannot have non-static semantics because there can be no parent class to refer to. Therefore, there is no way to change the default for top-level classes.
So, I'm coming late to the party, but here's my two cents - philosophically adding to Colin Hebert's answer.
At a high level your question deals with the difference between objects and types. While there are many cars (objects), there is only one Car class (type). Declaring something as static means that you are operating in the "type" space. There is only one. The top-level class keyword already defines a type in the "type" space. As a result "public static class Car" is redundant.
Class with private constructor is static.
Declare your class like this:
public class eOAuth {
private eOAuth(){}
public final static int ECodeOauthInvalidGrant = 0x1;
public final static int ECodeOauthUnknown = 0x10;
public static GetSomeStuff(){}
}
and you can used without initialization:
if (value == eOAuth.ECodeOauthInvalidGrant)
eOAuth.GetSomeStuff();
...
You can create a utility class (which cannot have instances created) by declaring an enum type with no instances. i.e. you are specificly declaring that there are no instances.
public enum MyUtilities {;
public static void myMethod();
}
Sure they can, but only inner nested classes. There, it means that instances of the nested class do not require an enclosing instance of the outer class.
But for top-level classes, the language designers couldn't think of anything useful to do with the keyword, so it's not allowed.
public class Outer {
public static class Inner {}
}
... it can be declared static - as long as it is a member class.
From the JLS:
Member classes may be static, in which case they have no access to the instance variables of the surrounding class; or they may be inner classes (ยง8.1.3).
and here:
The static keyword may modify the declaration of a member type C within the body of a non-inner class T. Its effect is to declare that C is not an inner class. Just as a static method of T has no current instance of T in its body, C also has no current instance of T, nor does it have any lexically enclosing instances.
A static keyword wouldn't make any sense for a top level class, just because a top level class has no enclosing type.
As explained above, a Class cannot be static unless it's a member of another Class.
If you're looking to design a class "of which there cannot be multiple instances", you may want to look into the "Singleton" design pattern.
Beginner Singleton info here.
Caveat:
If you are thinking of using the
singleton pattern, resist with all
your might. It is one of the easiest
DesignPatterns to understand, probably
the most popular, and definitely the
most abused.
(source: JavaRanch as linked above)
In addition to how Java defines static inner classes, there is another definition of static classes as per the C# world [1]. A static class is one that has only static methods (functions) and it is meant to support procedural programming. Such classes aren't really classes in that the user of the class is only interested in the helper functions and not in creating instances of the class. While static classes are supported in C#, no such direct support exists in Java. You can however use enums to mimic C# static classes in Java so that a user can never create instances of a given class (even using reflection) [2]:
public enum StaticClass2 {
// Empty enum trick to avoid instance creation
; // this semi-colon is important
public static boolean isEmpty(final String s) {
return s == null || s.isEmpty();
}
}
Everything we code in java goes into a class. Whenever we run a class JVM instantiates an object. JVM can create a number of objects, by definition Static means you have the same set of copy to all objects.
So, if Java would have allowed the top class to be static whenever you run a program it creates an Object and keeps overriding on to the same Memory Location.
If You are just replacing the object every time you run it whats the point of creating it?
So that is the reason Java got rid of the static for top-Level Class.
There might be more concrete reasons but this made much logical sense to me.
The only classes that can be static are inner classes. The following code works just fine:
public class whatever {
static class innerclass {
}
}
The point of static inner classes is that they don't have a reference to the outer class object.
I think this is possible as easy as drink a glass of coffee!.
Just take a look at this.
We do not use static keyword explicitly while defining class.
public class StaticClass {
static private int me = 3;
public static void printHelloWorld() {
System.out.println("Hello World");
}
public static void main(String[] args) {
StaticClass.printHelloWorld();
System.out.println(StaticClass.me);
}
}
Is not that a definition of static class?
We just use a function binded to just a class.
Be careful that in this case we can use another class in that nested.
Look at this:
class StaticClass1 {
public static int yum = 4;
static void printHowAreYou() {
System.out.println("How are you?");
}
}
public class StaticClass {
static int me = 3;
public static void printHelloWorld() {
System.out.println("Hello World");
StaticClass1.printHowAreYou();
System.out.println(StaticClass1.yum);
}
public static void main(String[] args) {
StaticClass.printHelloWorld();
System.out.println(StaticClass.me);
}
}
One can look at PlatformUI in Eclipse for a class with static methods and private constructor with itself being final.
public final class <class name>
{
//static constants
//static memebers
}
if the benefit of using a static-class was not to instantiate an object and using a method then just declare the class as public and this method as static.

Categories

Resources