I'm learning Java and as I know only abstract classes and interfaces cannot be instantiated. However documentation of java.lang.System says that it cannot be instantiated which is neither abstract nor an interface.
I haven't got any explanation of it. Can somebody please explain this ?
Moreover Can somebody create such classes ?
It's simple: It have no public Constructor.
You can do that yourself:
final public class Abc {
private Abc() {}
}
java.lang.System is java's version of a "static" class, meaning a class with only static methods and which does not require, or allow, an instance to be created before being used.
Since java doesn't allow the keyword "static" for class definitions (like C#), the best way to achieve such a static class is to make it's constructor private. For instance:
public final class System {
private System() { throw new UnsupportedOperationException(); }
public static void method1() { ... }
...other public static methods
}
This isn't fool proof, ie. checked by the compiler, but would restrict the class to only be created from within one of it's own methods, which the programmer is expected to know not to do (and will be reminded so by the exception if they should forget).
To instantiate a class you need a visible constructor. java.lang.System doesn't provide one, though.
Easy: Make a class final, so it can't be extended and let it have a private constructor, so a new System() won't work.
That's how System works.
You cannot instantiate a class which doesn't have public constructor, juste create a class with a private constructor and make it final so no other class can extend it :
public final class MyClass {
private MyClass() {
}
}
Note that you'll either need a public static member which will instantiate an object of the class for you (c.f. the Singleton pattern), or only static members.
Related
I have a use case with a class existing in 2 versions of a package.
package packageV1;
public class MyClass extends BaseClass{
public static String example(){
return "Version1";
}
}
package packageV2;
public class MyClass extends BaseClass{
public static String example(){
return "Version2";
}
}
So far so good (I believe).
Then I have an application using that class, and to avoid rewriting the application for the different package version, I want to pass the class that should be use (ie for the package of interest) as argument to the application.
So something like
public class Application{
private Class<BaseClass> selectedClass;
public void Application(Class<BaseClass> selectedClass){
this.selectedClass = selectedClass;
this.selectedClass.example(); // not possible
}
}
I believe I could call this.selectedClass.example(); if I were passing an instance of MyClass in the constructor, but then I would call static methods through a instance object, not nice right ?
On the other hand, in the example above selectedClass is a Class object, so I can't call the static method example as above.
Does this mean I should use reflection ? like selectedClass.getMethod(name, parameterTypes).
Looks overly complicated to me.
Or is there a better design ?
#javadev is right. Using reflection is almost always a really bad idea. It is that which over complicates.
There is no need for reflection here. The ability to invoke static methods on instances was rapidly realised to be a design error. So much so that there is a subsequent highly unorthogonal design choice in that it does not work for static methods that are members of interfaces.
The simple solution is to move the static methods to instance methods of stateless objects. No Class, or other reflection, necessary. This is an application of the Strategy design pattern.
Using a static method this way is not a good design, and not according to the Object Orinted principles.
My tip is to try changing "example()" to be a regular method, and not static.
I am having trouble understanding this.
"Lastly, modify WordTransformer and SentenceTransformer so you can not create an instance of the class. Remember, with static methods and variables, you do not need to make an instance of a class. (Hint: a constructor of a class is what allows an instance of that class to be created...new WordTransformer(), what keyword can you add to the definition of that constructor that will prevent the construct from being called anywhere but in the class itself?)"
It says so you can not create an instance of this class, but if you make the class private it becomes an error. Says the only options are public static or final.
well you shall qualify the constructor as private, not the class. cf this document:
Private constructors prevent a class from being explicitly instantiated by its callers.
here's an example:
public class WordTransformer {
private WordTransformer() {
}
}
N.B.: as it sounds a lot like an assignment, I hope that you'll read the linked documentation and understand why and when to use it!
Make the constructor private:
private WordTransformer(){}
private WordTransformer(...) {
...
}
Making the constructor private will allow other methods of this class to create instances of the class but no one can create instances from the outside. Example of when this is used in practice is the singleton pattern or builder pattern.
Private constructor and static methods on a class marked as final.
I have a class that offers a collection of static utility-type methods.
On the one hand, I don't want the class to be able to be instantiated. On the other hand, I don't want to send the signal that the class should be inherited from (not that I think that it's likely).
Should this class be abstract or not?
make the class final and make the default constructor private and do not provide any public constructors. that way no one can subclass it or create an instance of it.
Don't declare it abstract; declare a private constructor, so no one, not even a subclass, can instantiate an instance of your utility class.
You can declare your class final, although if all constructors are private, then no one will be able to subclass it anyway.
To borrow the idea from Pshemo's comment in another answer, throw a RuntimeException in the constructor to prevent reflection's setAccessible method in AccessibleObject from allowing instantiation:
public class MyUtility
{
private MyUtility()
{
throw new RuntimeException("Instantiation of MyUtility is not allowed!");
}
public static void utilityMethod()
{
// Your utility method here.
}
}
Although a top-level class can't be declared static, you can make the class non-instantiable (and practically 'static') to other classes by declaring the default constructor private, which forbids instantiation because no constructor is visible.
Another version of #mre's answer
enum MyClass{
;//this semicolon indicates that this enum will have no instances
//now you can put your methods
public static void myMethod(){
//...
}
}
Enum by default is final and its constructor is private. Also you cant create its instance with reflection because it checks in Constructor#newInstance if you are trying to instantiate Enum object.
What is contained in a class has no bearing on whether it should be abstract. The key take away: an abstract class must have another class extending it (a 'concrete' class); only that concrete class can be instantiated.
To prevent it from being extended, use final.
To prevent it from being instantiated, make the constructor private.
Observe that in Java these are discrete concepts.
No, it is a utility class.
It should be final with a private default constuctor, to avoid instantiation.
If you have checkstyle enabled you would get a warning if you dont do it.
Seriously, you don't have to do anything. Nothing bad will happen, nobody is going to instantiate/subclass your class.
In addition to all the other calls to give the class a private constructor, you should also make it final so that it is clear nothing can subclass it.
public final class Utils
{
// prevent accidental construction.
private Utils()
{
}
public static void foo()
{
//util code here
}
}
I have a quite simple question:
I want to have a Java Class, which provides one public static method, which does something. This is just for encapsulating purposes (to have everything important within one separate class)...
This class should neither be instantiated, nor being extended. That made me write:
final abstract class MyClass {
static void myMethod() {
...
}
... // More private methods and fields...
}
(though I knew, it is forbidden).
I also know, that I can make this class solely final and override the standard constructor while making it private.
But this seems to me more like a "Workaround" and SHOULD more likely be done by final abstract class...
And I hate workarounds. So just for my own interest: Is there another, better way?
You can't get much simpler than using an enum with no instances.
public enum MyLib {;
public static void myHelperMethod() { }
}
This class is final, with explicitly no instances and a private constructor.
This is detected by the compiler rather than as a runtime error. (unlike throwing an exception)
Reference: Effective Java 2nd Edition Item 4 "Enforce noninstantiability with a private constructor"
public final class MyClass { //final not required but clearly states intention
//private default constructor ==> can't be instantiated
//side effect: class is final because it can't be subclassed:
//super() can't be called from subclasses
private MyClass() {
throw new AssertionError()
}
//...
public static void doSomething() {}
}
No, what you should do is create a private empty constructor that throws an exception in it's body. Java is an Object-Oriented language and a class that is never to be instantiated is itself a work-around! :)
final class MyLib{
private MyLib(){
throw new IllegalStateException( "Do not instantiate this class." );
}
// static methods go here
}
No, abstract classes are meant to be extended. Use private constructor, it is not a workaround - it is the way to do it!
Declare the constructor of the class to be private. That ensure noninstantiability and prevents subclassing.
The suggestions of assylias (all Java versions) and Peter Lawrey (>= Java5) are the standard way to go in this case.
However I'd like to bring to your attention that preventing a extension of a static utility class is a very final decision that may come to haunt you later, when you find that you have related functionality in a different project and you'd in fact want to extend it.
I suggest the following:
public abstract MyClass {
protected MyClass() {
}
abstract void noInstancesPlease();
void myMethod() {
...
}
... // More private methods and fields...
}
This goes against established practice since it allows extension of the class when needed, it still prevents accidental instantiation (you can't even create an anonymous subclass instance without getting a very clear compiler error).
It always pisses me that the JDK's utility classes (eg. java.util.Arrays) were in fact made final. If you want to have you own Arrays class with methods for lets say comparison, you can't, you have to make a separate class. This will distribute functionality that (IMO) belongs together and should be available through one class. That leaves you either with wildly distributed utility methods, or you'd have to duplicate every one of the methods to your own class.
I recommend to never make such utility classes final. The advantages do not outweight the disadvantages in my opinion.
You can't mark a class as both abstract and final. They have nearly opposite
meanings. An abstract class must be subclassed, whereas a final class must not be
subclassed. If you see this combination of abstract and final modifiers, used for a class or method declaration, the code will not compile.
This is very simple explanation in plain English.An abstract class cannot be instantiated and can only be extended.A final class cannot be extended.Now if you create an abstract class as a final class, how do you think you're gonna ever use that class, and what is,in reality, the rationale to put yourself in such a trap in the first place?
Check this Reference Site..
Not possible. An abstract class without being inherited is of no use and hence will result in compile time error.
Thanks..
How to run the method foo() in class A without any changes on this class
public final class A{
private A(){
System.exit(0);
}
public void foo(){
System.out.println("from foo");
}
}
Without doing something like using reflection or bytecode manipulation to mess with accessibility...
The "right" way to do this is to get an instance of the class some other way. For example, if there's a static factory method or pre-made instances that you can access. The reason for having a private constructor like this is to control construction of the class. (For example, enum implementations have a private constructor so that you don't create additional instances beyond the static ones supplied.)
If you side-step this then someone (either you or the original class author) is doing something wrong.
You can create an instance of a class without calling the constructor. See this question: Is it possible to create an instance of an object in Java without calling the constructor?
You can use objenesis to do this for you. Once you've got an instance of A without calling the constructor, calling foo is easy.
You can alter the byte code before it is loaded by the jvm. Here's a place to start:
http://www.ibm.com/developerworks/java/library/j-dyn0916/index.html