Why can't we create instance of Collections class (not Collection Interface)? - java

Collections is a public class, then we can call its implicit default constructor. It doesn't have private constructor, which would prevent object creation or force to have static factory method. When I do instantiate as new Collections(), i get error as "Constructor not visible". In short why can't we have instance of java.util.Collections class? Thanks.

From the documentation: "This class consists exclusively of static methods that operate on or return collections."
In other words, Collections is just a collection of methods. An instance of it would not make any sense. It is just like the math functions: You don't have an instance of math, you just use the functions.
It is not an interface as it has concrete methods.

The reason for the "Constructor not visible" message is that the constructor is private (line 73), or at least according to this site . And as others already stated, what would you do with an instance of this class as it only contains static methods
// Suppresses default constructor, ensuring non-instantiability.
private Collections() {
}

Related

Static Factory methods

As per Joshu Bloch's Effective Java,"The main disadvantage of providing only static factory methods is that classes without public or protected constructors cannot be subclassed." Can someone please explain what does this mean? Especially the bolded words. If a static factory method is provided or not, class with private constructor can't be subclassed right?
Providing only static factory methods is that classes without public
or protected constructors cannot be subclassed.
Whenever a constructor of a subclass is called, the constructor of the parent class is also called. In the absence of protected or public constructors, sub classing or extending a class will make no sense. Hence the disadvantage.
Java requires from derived class to ensure that inherited fields will be properly initialized. It is done by making at start of constructor call to constructor of superclass.
Such code should look like
class Derived class Parent{
public Derived(){
super();//this will be added automatically by compiler
//or super(arguments) if you want to use constructor with arguments
}
}
But if superclass doesn't make its constructor accessible (it is privet) derived class can't add super call in any of its constructor. This means that we can't create valid code for constructor, and since all classes must have at least one constructors derived class can't compile.

Java : final constructor [duplicate]

Why can't constructors be final, static, or abstract in Java?
For instance, can you explain to me why this is not valid?
public class K {
abstract public K() {
// ...
}
}
When you set a method as final it means: "I don't want any class override it." But according to the Java Language Specification:
JLS 8.8 - "Constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding."
When you set a method as abstract it means: "This method doesn't have a body and it should be implemented in a child class." But the constructor is called implicitly when the new keyword is used so it can't lack a body.
When you set a method as static it means: "This method belongs to the class, not a particular object." But the constructor is implicitly called to initialize an object, so there is no purpose in having a static constructor.
The question really is why you want constructor to be static or abstract or final.
Constructors aren't inherited so can't be overridden so whats the use
to have final constructor
Constructor is called automatically when an instance of the class is
created, it has access to instance fields of the class. What will be
the use of a static constructor.
Constructor can't be overridden so what will you do with an abstract
constructor.
A Java constructor is implicitly final, the static / non-static aspects of its semantics are implicit1, and it is meaningless for a Java constructor to be abstract.
This means that the final and static modifiers would be redundant, and the abstract keyword would have no meaning at all.
Naturally, the Java designers didn't see in any point in allowing redundant and/or meaningless access modifiers on constructors ... so these are not allowed by the Java grammar.
Aside: It is a shame that they didn't make the same design call for interface methods where the public and abstract modifiers are also redundant, but allowed anyway. Perhaps there is some (ancient) historical reason for this. But either way, it cannot be fixed without rendering (probably) millions of existing Java programs uncompilable.
1 - Actually, constructors have a mixture of static and non-static semantics. You can't "call" a constructor on an instance, and it they are not inherited, or overridable. This is similar to the way static methods work. On the other hand, the body of a constructor can refer to this, and call instance methods ... like an instance method. And then there is constructor chaining, which is unique to constructors. But the real point is that these semantics are fixed, and there is no point allowing a redundant and probably confusing static modifier.
public constructor: Objects can be created anywhere.
default constructor: Objects can be created only in the same package.
protected constructor: Objects can be created by classes outside the package only if it's a subclass.
private constructor: Object can only be created inside the class (e.g., when implementing a singleton).
The static, final and abstract keywords are not meaningful for a constructor because:
static members belong to a class, but the constructor is needed to create an object.
An abstract class is a partially implemented class, which contains abstract methods to be implemented in child class.
final restricts modification: variables become constant, methods can't be overridden, and classes can't be inherited.
Final: Because you can't overwrite/extend a constructor anyway. You can extend a class (to prevent that you make it final) or overwrite a method (to prevent that you make it final), but there is nothing like this for constructors.
Static: If you look at the execution a constructor is not static (it can access instance fields), if you look at the caller side it is (kind of) static (you call it without having an instance. Its hard to imagine a constructor being completely static or not static and without having a semantic separation between those two things it doesn't make sense to distinguish them with a modifier.
Abstract: Abstract makes only sense in the presence of overwriting/extension, so the same argument as for 'final' applies
No Constructors can NEVER be declared as final. Your compiler will always give an error of the type "modifier final not allowed"
Final, when applied to methods, means that the method cannot be overridden in a subclass.
Constructors are NOT ordinary methods. (different rules apply)
Additionally, Constructors are NEVER inherited. So there is NO SENSE in declaring it final.
Constructors are NOT ordinary methods. (different rules apply)
Additionally, Constructors are NEVER inherited. So there is NO SENSE in declaring it final.
No Constructors can NEVER be declared final. YOur compiler will always give an error of the type "modifer final not allowed"
Check the JLS Section 8.8.3 (The JLS & API docs should be some of your primary sources of information).
JLS section 8 mentions this.
Constructors (§8.8) are similar to methods, but cannot be invoked
directly by a method call; they are used to initialize new class
instances. Like methods, they may be overloaded (§8.8.8).
But constructors per say are not regular methods. They can't be compared as such.
why constructor can not be static and final are well defined in above answers.
Abstract: "Abstract" means no implementation . and it can only be implemented via inheritance. So when we extends some class, all of parent class members are inherited in sub-class(child class) except "Constructor". So, lets suppose, you some how manage to declare constructor "Abstract", than how can you give its implementation in sub class, when constructor does not get inherit in child-class?
that's why constructor can't be
abstract .
lets see first
final public K(){
*above the modifier final is restrict 'cause if it final then some situation where in some other class or same class only we will override it so thats not gonna happen here proximately not final
eg:
we want public void(int i,String name){
//this code not allowed
let static,, static itz all about class level but we create the object based constructor by using 'new' keyword so,,,,,, thatsall
abstract itz worst about here not at 'cause not have any abstract method or any declared method
Unfortunately in PHP the compiler does not raise any issue for both abstract and final constructor.
<?php
abstract class AbstractClass
{
public abstract function __construct();
}
class NormalClass
{
public final function __construct() {
echo "Final constructor in a normal class!";
}
}
In PHP static constructor is not allowed and will raise fatal exception.
Here in AbstractClass obviously a constructor either can be declared as abstract plus not implemented or it can be declared as something among (final, public, private, protected) plus a function body.
Some other related facts on PHP:
In PHP having multiple constructor __construct() is not possible.
In PHP a constructor __construct() can be declared as abstract, final, public, private and protected!
This code was tested and stood true for in PHP versions from 5.6 up to 7.4!

How is my private member getting set to null?

I have been programming java professionally for more than ten years. This is one of the weirdest bugs I've ever tried to track down. I have a private member, I initialize it and then it changes to null all by itself.
public class MyObject extends MyParent
{
private SomeOtherClass member = null;
public MyObject()
{
super();
}
public void callbackFromParentInit()
{
member = new SomeOtherClass();
System.out.println("proof member initialized: " + member);
}
public SomeOtherClass getMember()
{
System.out.println("in getMember: " + member);
return member;
}
}
Output:
proof member initialized: SomeOtherClass#2a05ad6d
in getMember: null
If you run this code, obviously it will work properly. In my actual code there are only these three occurrences (five if you count the printlns) in this exact pattern.
Have I come across some bug in the JVM? Unless I'm wrong, the parent class can't interfere with a private member, and no matter what I put between the lines of code I've shown you, I can't change the value of member without using the identifier "member".
This happens because of the order in which member variables are initialized and constructors are called.
You are calling callbackFromParentInit() from the constructor of the superclass MyParent.
When this method is called, it will set member. But after that, the subclass part of the object initialization is performed, and the initializer for member is executed, which sets member to null.
See, for example:
What's wrong with overridable method calls in constructors?
State of Derived class object when Base class constructor calls overridden method in Java
Using abstract init() function in abstract class's constructor
In what order constructors are called and fields are initialized is described in paragraph 12.5 of the Java Language Specification.
Assignment of null to field member happens after executing parent constructor.
The fix is to change:
private SomeOtherClass member = null;
to:
private SomeOtherClass member;
Never, never ever call a non final method from the superclass' constructor.
It's considered bad practice, precisely because it can lead to nasty, hard-to-debug errors like the one you're suffering.
Perform initialization of a class X within X's constructor. Don't rely on java's initialization order for hierarchies. If you can't initialize the class property i.e. because it has dependencies, use either the builder or the factory pattern.
Here, the subclass is resetting the attribute member to null, due to superclass and subclass constructors and initializer block execution order, in which, as already mentioned, you shouldn't rely.
Please refer to this related question for concepts regarding constructors, hierarchies and implicit escaping of the this reference.
I can only think about sticking to a (maybe incomplete) set of rules/principles to avoid this problem and others alike:
Only call private methods from within the constructor
If you like adrenaline and want to call protected methods from within the constructor, do it, but declare these methods as final, so that they cannot be overriden by subclasses
Never create inner classes in the constructor, either anonymous, local, static or non-static
In the constructor, don't pass this directly as an argument to anything
Avoid any transitive combination of the rules above, i.e. don't create an anonymous inner class in a private or protected final method that is invoked from within the constructor
Use the constructor to just construct an instance of the class, and let it only initialize attributes of the class, either with default values or with provided arguments

Java - is it bad practice not to have a class constructor?

I want to make a helper class that deals with formatting (i.e. has methods to remove punctuation and convert between types, as well as reformatting names etc.). This doesn't seem like it will need any fields - its only purpose is to get passed things to convert and return them, reformatted. Is it bad practice to leave out a constructor? If so, what should my constructor be doing? I was looking at this link and noticed that the class it describes lacks a constructor.
Is it bad practice to leave out a constructor?
Yes - because unless you specify any constructors, the Java compiler will give you a constructor with the same visibility as the class itself.
Assuming all your methods are static - which seems likely unless you want polymorphism - you should make your class final and give it a private constructor, so that other developers don't accidentally create an instance of your class, when that would be pointless. When thinking about an API, any time I can remove the ability for developers to do something stupid, I do so :)
So something like:
public final class Helpers {
private Helpers() {
}
public static String formatDate(Date date) {
// etc
}
}
Note that by taking polymorphism out of the equation, you're also removing the possibility of changing this behaviour for tests etc. That may well be fine - I'm not a believer in "no statics, ever" - but it's worth considering.
Any class that has all the methods which do not have or need any state is free to reduce the visibility of constructor by making the constructor private.
Example java.lang.Math class in Java.
As java.lang.Math has all static methods which do similar job as your class they have declared the constructor as private so that nobody can accidentally create the instance of that class.
/**
* Don't let anyone instantiate this class.
*/
private Math() {}
Not bad practice. but the example that you have given doesn't have any member variables that can be used in an Object context. In such situations, it's best to have static methods because then you don't need to allocate memory to create objects for the class before calling the methods.
Compiler will generate a default constructor (with no parameters) for you. If your class has not state and does not extend a class which needs initialization, you can let it without declaring explicit constructor
no its good to leave out a constructor as there aren't any instance variables in your class!
constructors are meant to initialize the instance variables!
still if you skip the constructor, compiler anyways inserts the default constructor which is fair enough!!
You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor.
Java Official Document: Providing Constructors for Your Classes
Usually it is a good coding practice to define your constructor in the class though each class has a default constructor .
But if you do not have any special need to use a oveloaded constructor or to make any singleton pattern then you can remove the constructor .
If you are using static methods in your case then also you dont have any need to define constructor , as you do not need to have object of this class .

Java Reflection - Methods Introspection

Method[] theMethods = myClass.getMethods();
for( Method m : theMethods ){
...
}
Will the array include all the methods of the class? public, private, protected and all inherited?
Will I have access to all of them mainly the private and protected ones?
If not, how can I get all the methods of a class and also have access to all?
The Javadoc makes this pretty clear:
Returns an array containing Method objects reflecting all the public member methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces.
To get at non-public methods, use getDeclaredMethods.
To get all methods of a class you need to recursively call getDeclaredMethods() on the class and all it's superclasses. Depending on what you want to achive with it you might need to remove duplicates which can occur due to method overloading.
From the API doc:
Returns an array containing Method
objects reflecting all the public
member methods of the class or
interface represented by this Class
object, including those declared by
the class or interface and those
inherited from superclasses and
superinterfaces.
So it gets you only public methods. To get all methods, you have to use getDeclaredMethods() on the class and all its superclasses (via getSuperclass()).
In order to call non-public methods, you can use setAccessible(true) on the Method object (if the security manager allows it).

Categories

Resources