I am new to programming and was studying "Head First Java", I just saw a problem where there was used Math class like this
int x= Math.round(float value);
and it was mentioned we don't need to instantiate Math class because its constructor is set private. What does that mean? Until now I read we need to instantiate that class and reference variable to play around with methods and instance variables of the class how does Math class work like this?
we don't need to instantiate Math class because its Constructor is set Private
Because all the methods in Math class are static you can use the class name to invoke them. So there is no use instantiating the class , hence the constructor was declared private. it will also prevent sub classing the Math class, since it is the only constructor.
Look at the open source code :
Don't let anyone instantiate this class.
private Math() {} // only constructor defined in Math class
The methods of Math class doesn't depend on the internal state of the class , they are just like utility functions . So it was wise to declare them as static. static methods can be invoked by directly using the classname , hence no use of instantiating the class. They belong to the class, not specific objects of that class.
You can refer the JLS 8.4.3.2 :
A class method is always invoked without reference to a particular object.
The Math class have all methods as a static, and you need to get the method from the class itself. No need to create instance variable to access Static variable and methods
Refer Math Class java doc. you find all method here static i,e. Math.round
Private constructors means that they can only be called upon from within the class to which they belong, a good example of the use of private constructors can be found here Can a constructor in Java be private?
Private constructors do however have nothing to do with the fact that you can use methods from the MATH class without instantiating them. This is because the methods of MATH class are static i.e. a static method can be called upon without instantiating an object of the class to which the methods belong.
As said in the comments above, you have no use of instantiating a MATH object, therefore the constructor is private, but you could use the MATH methods anyway had the constructor been public.
Related
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!
Why is it that even if you have declared a private static final variable, a color - defaultC, let's say - then you still cannot use this.defaultC in the super constructor (i.e. you can only use super(defaultC) and not super(this.defaultC) even though it is equivalent to simply defaultC.
I was simply trying to extend a Tile class to a Wall class and the Wall class I stored all of the necessary private static final variables for all walls (such as their width and height, another int and the default color), and the Tile class already has some of the variables (but they are protected not private). I didn't want the warning Field hides another field to pop up (because there Tile.java and Wall.java have the same names for many variables), so I used this. for my private static final variables, and there were errors galore.
It's not particularly troubling (as I simply have a few warnings), but I was simply wondering why. I am guessing that the compiler simply doesn't like it because you cannot reference this before the supertype, but there are still exactly the same. Has such a feature not been added yet that overlooks such a thing or is there another reason I cannot see that you cannot use super(this.PRIVATE_STATIC_FINAL_VARIABLE);?
A static variable does not belong to any instance of an object. The this keyword should refer to an instance of an object and variables used within. While you can use the this keyword to access static variables, you should not.
Also, a variable marked private in a super class cannot be accessed within a child class.
To reference a variable declared in a super class from a child class using the this keyword, that variable must be declared protected or public.
You could try to tie the static final variable to the class you're in when passing it to super. I believe you can do this by doing something like super(SubClass.PRIVATE_STATIC_FINAL_VARIABLE);
Here we have two things to know,
what is the meaning of static keyword.
what is the meaning of this keyword
what is a constructor
in java, there are two types, class and instance of an class. We can use a class without creating an instance of it, or after creating a instance of the class itself.
object is an instance of a class.
The keyword static is used with the class. this is used with instances of class. And this keyword refers the instance of the class it is used within.
An instance of an class(object) is created after calling the class's constructor. We can use keyword this only after creating an instance of class (inside the object).
As the constructor method is called before creating the instance of the class, We can't use this keyword inside a constructor. That's why you got an error in super(this.defaultC) but not in super(defaultC)
And you can't use this keyword inside constructor for PRIVATE_STATIC_FINAL_VARIABLE as well.
But you are allowed to use PRIVATE_STATIC_FINAL_VARIABLE without using this
i.e. super(PRIVATE_STATIC_FINAL_VARIABLE)
The "abstract" keyword means you cannot create an instance of the class (an object).
Java.Lang.Math is preceded with the following keywords
public final class Math {
...
}
But no "abstract" keyword. The class simply provides a collection of related static variables and methods, like PI and sin().
Static means that those variables/methods can't be unique between different instances of the object (there is only one copy of those variables/methods associated with the class itself). So why even allow the programmer to create an instance of the class? Why not precede with "abstract"?
final and abstract keywords can't be applied together because final class can't be overridden and abstract classes are meant for override.
A class that is declared final cannot be subclassed that is used for creating an immutable class such as String
It's better explained under JSL section - 8.1.1. Class Modifiers
An abstract class is a class that is incomplete, or to be considered incomplete.
A class can be declared final if its definition is complete and no subclasses are desired or required.
both above statements are contradicting each-other.
If you want to read more about then have a look at Java Tutroial on A Strategy for Defining Immutable Objects
Don't provide "setter" methods — methods that modify fields or objects referred to by fields.
Make all fields final and private.
Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
If the instance fields include references to mutable objects, don't allow those objects to be changed:
Don't provide methods that modify the mutable objects.
Don't share references to the mutable objects.
java.lang.Math is a Utility class (contains only static utility methods).
Correct way to define utility class is to make it final so that no other class can extend it and to have private no-args constructor so that no one can create an instance of the class.
So you won't be able to create instance of class any how. However if you go by abstract approach, you cannot use final and there is no way you can prevent it from being extended. Hence former approach is better.
If it were abstract, someone could do
public class NewMath extends Math {
which frankly speaking makes no sense.
However, you cannot create a new Math instance anyway because its only constructor is private:
private Math() {}
final means you cannot extend it, the reason you cannot create an instance is because the constructor is private. This is how (in java) you define static classes or factory classes.
The Abstract keyword means the class can't be Instantiable but it can be Extended.
And in case of Utility Classes such Math Class,Extending it has no sense. Declaring the no-args Constructor makes it Non-Instantiable and final makes it non-Extendable...So its the Perfect Match .... And If you use Abstract then you can't use Final...
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 .
It's been about 6 years since I've written Java, so please excuse the rust.
I'm working with a library method that requires that I pass it Class objects. Since I'll have to invoke this method a dynamic number of times, each time with a slightly different Class argument, I wanted to pass it an anonymous class.
However, all the documentation/tutorials I've been able to find so far only talk about instantiating anonymous classes, e.g.:
new className(optional argument list){classBody}
new interfaceName(){classBody}
Can I define an anonymous class without instantiating it? Or, perhaps more clearly, can I create a Class object for an anonymous class?
Unfortunately, there's no way you can dodge the instantiation here. You can make it a no-op, however:
foo((new Object() { ... }).getClass());
Of course, this might not be an option if you have to derive from some class that performs some actions in constructor.
EDIT
Your question also says that you want to call foo "each time with a slightly different Class argument". The above won't do it, because there will still be a single anonymous inner class definition, even if you put the new-expression in a loop. So it's not really going to buy you anything compared to named class definition. In particular, if you're trying to do it to capture values of some local variables, the new instance of your anonymous class that foo will create using the Class object passed to it will not have them captured.
short answer
you cannot (using only JDK classes)
long answer
give it a try:
public interface Constant {
int value();
}
public static Class<? extends Constant> classBuilder(final int value) {
return new Constant() {
#Override
public int value() {
return value;
}
#Override
public String toString() {
return String.valueOf(value);
}
}.getClass();
}
let's creating two new class "parametric" classes:
Class<? extends Constant> oneClass = createConstantClass(1);
Class<? extends Constant> twoClass = createConstantClass(2);
however you cannot instantiate this classes:
Constant one = oneClass.newInstance(); // <--- throws InstantiationException
Constant two = twoClass.newInstance(); // <--- ditto
it will fail at runtime since there is only one instance for every anonymous class.
However you can build dynamic classes at runtime using bytecode manipulation libraries such ASM. Another approach is using dynamic proxies, but this approach as the drawback that you can proxy only interface methods (so you need a Java interface).
You can only reference an anonymous class ONCE. If you do not instantiate it there, you cannot instantiate it since you do not have a name for it.
Hence I believe that anonymous classes can only be used in conjunction with a "new BaseClass()".
In your situation you would pass a BaseClass object to your method doing the work, and instantiate the anonymous object in the source code when you need the object to pass.
You can't access the Class object of an anonymous class without instatiating it. However, if you only need access to the class, you could define local classes within your method and refer to these using the ClassName.class literal syntax.
You can assume the name of an anonymous class and call Class.forName("mypackage.MyBaseClass$1") to get a handle to an anonymous class. This will give you the first anonymous class defined in your MyBaseClass, so this is a rather fragile way to refer to a class.
I suspect whatever you are trying to do could be done a better way. What are you really trying to achieve? Perhaps we can suggest a way which doesn't require you to pass a Class this way.
You can access the class object of an anonymous class by calling .getClass() on it immediately after creation. But what good would that do?
I think the key is in this part of what you said:
I'm working with a library method that requires that I pass it Class
objects.
Why does it want you to pass it Class objects? What does this library do with the Class objects you pass it? Instantiate objects? But if so, what constructor does it use and how does it decide what arguments to pass? I don't know what library you are using or what it does, but I would guess that it always creates objects using the no-argument constructor. However, that will not work for anonymous classes anyway, since they have no public constructor (and in any case, to instantiate any non-static inner class, a reference to the outer instance must be provided, so there is no no-argument constructor).