Java Final class or private constructor - java

When we want to close a class to inheritance we are declaring class with final,
final class Myclass {}
but when we declare the constructor private it will be the same effect,
class Myclass {
private Myclass() {}
}
But is it really the same? Is there any difference for optimization of code or readability of code? And which classes has to close to inheritance,
immutable class maybe
every method and member variable declared static of class
But for second option java.util.Arrays hasn't been declared with final even if all methods of Arrays are declared static.

but when we declare ctor private it will be the same effect
Not necessarily, consider this example using static classes:
public class SOExample {
private static class ClassWithPrivateConstructor {
private ClassWithPrivateConstructor() {
System.out.println("I have a private constructor");
}
}
private static class ClassThatExtendsClassWithPrivateConstructor extends ClassWithPrivateConstructor {
}
public static void main(String[] args) {
new ClassThatExtendsClassWithPrivateConstructor();
}
}
This will print "I have a private constructor".
but is it really same? is there any difference for optimization of code or readablity of code. and which classes has to close to inheritance,
When a developer sees that a class is final, they understand that the intention of the author was that it should not be extended.
When a developer sees that a class has a private constructor, they understand that the class can't be instantiated. This is generally because it is either a static utility class or a singleton.
But for second option java.util.Arrays hasn't declared with final even if all methods of Arrays declared static
This is a good observation. My guess is that it probably should have been but can't be changed now for backward compatibility.

What I usually do is I make the class final and the constructor private:
it removes the ambiguity about the class use (emphasising it's a utility class)
it keeps the user away from what they aren't supposed to do (to initiate, to extend).
.
#NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class HttpTool {}
That said, there is nothing wrong with java.util.Arrays. The designer achieves the desired effect (non-instantiability) with the necessary minimum (the private constructor).

If you want to create an immutable class or just a class that for some reason should not have childrens you should declare it as final. Private constructor should be used in utility classes, this way you block inheritance and also make sure instance of the class cannot be created.

Related

Java - Private member vs default member of a private inner class

Since an enclosing class can access the private fields of its inner class, when should be they declared private, default or public for a private inner class?
At first glance, it seems irrelevant to specify an access modifier on the members of inner classes. As you pointed out, the containing class can access all members anyway.
Here are a few additional considerations though:
Sometimes inner classes are declared public and serve as part of the interface definition of the containing class. Perhaps the outer class has a method that returns an instance of the inner class. In this case, the inner class is subject to the same best practices for member visibility as top-level classes. It's preferrable to keep implementation details private in this case.
Although it wouldn't be enforced by the compiler, marking an inner class's members as private can document for future maintainers that those members are not intended to be accessed directly by the outer class code. Of course, at that point, it might warrant refactoring the inner class to its own top-level class.
Sometimes inner classes are used in combination with reflection-based frameworks that only operate on public members. For example, the Jackson JSON serializer by default only operates on public members. It is possible to make it operate on private members by doing a few things like adding a public getter. This is extra work, so it may be more convenient to declare the member public in the first place.
If the above points do not apply, and in the absence of any other requirements, the simplest and shortest code is to omit the access modifier entirely (default/package-private). This would be a coding style question for a project to consider.
It's a good style to declare everything private unless there is a reason to use package private or public visibility. And this reason should not be it's more convenient.
Everything that is not private may be used outside of your class and thus changes to any non-private aspect of your code may break other code places or even external code that relies on your code. Making more difficult or sometimes even impossible to do refactorings and change the inner workings of your classes.
In the special case of a private inner class everything is only visible to your containing class. That is the visibility of the inner classes' members is not of importance. To the other extreme, if you are working on a library its common practice to only expose interfaces as contract. Keeping the implementation details completely hidden.
Not only the outer class but also other classes can access inner class and its members .So when you want to make the inner class members accessible by only its outer class you can declare them as private . consider the fallowing example
There are 2 classes in same package com.exercise.test and classes in it are OtherClass and SampleClassWithInner which contains inner class InnerClass
the members of InnerClass declared as private is not accessible in OtherClass. Where as it is accessible in SampleClassWithInner
refer this code for more clarity
package com.exercise.test;
//import com.exercise.test.SampleClassWithInner.InnerClass;
public class OtherClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
SampleClassWithInner sampleobj = new SampleClassWithInner();
SampleClassWithInner.InnerClass innerobj = sampleobj.new InnerClass();
// innerobj.var1=5; //compile time error
innerobj.setVar1(5); // ok works
// System.out.println("value of inner variable declared in other
// class"+innerobj.var1);// compile time error
System.out.println("value of inner variable declared in other class "
+ innerobj.getVar1());
sampleobj.innerMethodDemo();
}
}
and
package com.exercise.test;
public class SampleClassWithInner {
class InnerClass {
private int var1;
private int var2;
public int getVar1() {
return var1;
}
public void setVar1(int var1) {
this.var1 = var1;
}
public int getVar2() {
return var2;
}
public void setVar2(int var2) {
this.var2 = var2;
}
}
public void innerMethodDemo() {
InnerClass obj = new InnerClass();
obj.var1 = 10;
System.out.println("this is form the method in outer class " +
obj.var1);
}
}

Can Util class can be abstract or final?

public final class DateUtil{
public static void t1();
}
public abstract class DateUtil{
public static void t1();
}
abstract classes are meant to be sub-classed, and their sub-classes are meant to be instantiated, so they are not a good fit for utility classes.
If you are asking about a class that contains only static utility methods and shouldn't be instantiated, make it final and make the constructor private. That's what the JDK developers did with classes such as java.lang.Math.
Yes. Either or neither.
General opinion is that it should not be subclassable or instantiable, so add a private constructor. (Some people disagree.)
private DateUtil() {
throw new Error();
}
In general, all Util classes are final and static. It will have private constructor.
So that anyone who is calling the method ,no need to create object and can directly access with class name.

Variables in private interface

I was trying to test working of private interfaces and wrote the code below. I can understand that a situation might arise to declare private interfaces if we don't want any other class to implement them but what about variables? Interface variables are implicitly public static final and hence i was able to access them even if interface was declared private. This can be seen in code below.
public class PrivateInterfaceTest {
/**
* #param args
*/
public static void main(String[] args) {
TestingInterfaceClass test = new TestingInterfaceClass();
TestingInterfaceClass.inner innerTest = test.new inner();
System.out.println(innerTest.i);
}
}
class TestingInterfaceClass {
private interface InnerInterface {
int i = 0;
}
class inner implements InnerInterface {
}
}
Does it mean that we can never really have private interface in true sense? And does it really make sense to if have private interface if we can access variables outside private interface?
EDIT:
Just want to add that same situation will not arise if we have private inner class. A private variable in inner class will never get exposed.
Your member interface is private. The inherited static field is not private.
A private member interface cannot be used as a type outside the enclosing top-level class or enum. This can be useful to prevent external code from implementing an interface you may wish to change. From the JLS:
The access modifiers protected and private pertain only to member interfaces within a directly enclosing class or enum declaration (§8.5.1).
The interface field is public, and inherited by the class that implements the interface. From the JLS:
A class inherits from its direct superclass and direct superinterfaces all the non-private fields of the superclass and superinterfaces that are both accessible to code in the class and not hidden by a declaration in the class.
If you want to make the field accessible only within the classes that implement the member interface, you can put its declaration in the enclosing top-level scope.
class TestingInterfaceClass {
private static final int i = 0;
private interface InnerInterface {
// ...
}
class inner implements InnerInterface {
// ...
}
}
As I see, it is not the problem with private interface InnerInterface. It is the inner class which is at default scope inside TestingInterfaceClass exposing the content of InnerInterface. If you don't want the content of InnerInterface to be known to the world, you should also declare all the classes (specifically TestingInterfaceClass) as private.
Because every variable in an interface is public static final, it should be the responsibility of the class (implementing it) whether it should take care of the content inherited from private interface
Even though it's allowed, we don't need (and shouldn't use) an instance to access an static field.
Following is the way to access it -
System.out.println(TestingInterfaceClass.inner.i);
//note you cannot access the InnerInterface like this here because it's private
The inner has inherited the public static field i and i should be visible wherever the inner itself is visible.
Usually, interfaces are used to expose the behaviors of an object, while the implementations are hidden. But in your case, you are attempting the opposite.
The Interface variables are implicitly public static final, but you can't reach this variables because you can't reach previously the interface that contains these variable, which you have declared as private. First you need to be able to see the interface, and after that, go into content of the interface.

non-static variable this cannot be referenced from a static context - why here?

I have a code:
package why;
public class Foo
{
public class Foo1
{
String bar;
public Foo1(String bar)
{
this.bar = bar;
}
public static Foo1 MYCONSTANT = new Foo(null);
}
}
Why do I get 'non-static variable this cannot be referenced from a static context'?
I allocate the instance of non-static class.
Why even here?
public static Foo getMYCONSTANT()
{
return new Foo(null, null);
}
Thank you
Lets take a look at this example:
public class MainClass {
public class NonStaticClass {
public static NonStaticClass nonStatic = new NonStaticClass();
//Compile error: The field nonStatic cannot be declared static;
//static fields can only be declared in static or top level types
public static int i = 10;//this field also causes the same compile error
}
}
The problem is that NonStaticClass is, well, not static. A non static inner class can't contain static fields.
If you want to have a static field in the inner class you need to make the class static.
From the java documentation:
Inner Classes
As with instance methods and variables, an inner class is associated
with an instance of its enclosing class and has direct access to that
object's methods and fields. Also, because an inner class is
associated with an instance, it cannot define any static members
itself.
For more information take a look at Nested Classes
I'm not sure what your real question is ... but perhaps this might help:
http://en.wikipedia.org/wiki/Singleton_pattern
In the second edition of his book "Effective Java" Joshua Bloch claims
that "a single-element enum type is the best way to implement a
singleton"[9] for any Java that supports enums. The use of an enum is
very easy to implement and has no drawbacks regarding serializable
objects, which have to be circumvented in the other ways.
public enum Singleton {
INSTANCE;
}

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