This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When should one use final?
When should Java programmers prefer to use
final Date now = new Date();
over
Date now = new Date();
Apart from deciding if a variable should be final or not which is covered in other posts, I think the problem with final Date now = ..., is that although the reference to now will not change (it is final), its value might. So I find this a little misleading for developers who don't know that Date is mutable.
For example, you could write:
public static void main(String[] args) {
final Date now = new Date();
System.out.println(now);
now.setHours(5);
System.out.println(now);
}
and get 2 different dates out of your final date...
Now this is true for any mutable variable (the content of final List<String> l can change too), but I think in the case of a Date, it is way too easy to assume immutability.
A better solution would be using the joda time library:
final DateTime now = new DateTime();
in this case, now is immutable and won't change (reference & value).
In Java, a final variable is a variable whose value, once assigned, cannot be changed. You declare a variable final when that variable will be assigned a value, and you will never need to change that value.
When you use final keyword you can never change the value of variable.Same apply for date.
A final variable can be explicitly initialized only once. A reference variable declared final can never be reassigned to refer to an different object.
However the data within the object can be changed. So the state of the object can be changed but not the reference.
With variables, the final modifier often is used with static to make the constant a class variable.
Example:
class Test{
final int value=10;
// The following are examples of declaring constants:
public static final int BOXWIDTH = 6;
static final String TITLE = "Manager";
public void changeValue(){
value = 12; //will give an error
}
}
if your requirement is of this type than you can use final with date.
If you declare a field, which is read-only, and you want to have a class thread-safe - then you should use the final modifier. Sometimes you're forced to make a variable final, if it's used in an anonymous class. In all other cases it doesn't really matter.
Related
In the following example, x can be changed by class B even though it's a private member of class A. What's the reason for this?
import java.util.Date;
class A {
private Date x;
public A(){
super();
x = new Date();
}
public Date getDate(){
return x;
}
public void print(){
System.out.println(this.x);
}
}
class B {
public static void main(String[] args){
A a = new A();
a.print();
Date d = a.getDate();
d.setMonth(12);
System.out.println(d);
a.print();
}
}
The output is:
Initial date generated by A
Date changed by B
Date changed by B (why does it change a private member here?)
private prevents a variable from being accessed directly by another class. You cannot write d.x to read or write to x.
If the class chooses to return a reference to x via a public method, though, that's it's own choice to pierce the veil of privacy. Nothing stops A from allowing x to be read from a getter or modified from a setter.
In recent years the Java community has recognized the problem with this: namely, if you return a reference to a private mutable object, you open the door for your class's internal state to be mucked with without its knowledge. To protect against this, it has become good practice to make classes immutable whenever possible.
Indeed, Date is a perfect example of a poorly-designed mutable class. The java.time package introduced in Java 8 added a slew of immutable time and date classes to replace Date. You can now return a private Instant and not worry about callers being able to change it.
It's important to point out that immutability comes from how a class is defined. It's not a language-level feature like private. Confusingly, final can be used to make variables immutable, but applying it to a class does not make the class immutable (it makes it unextendable).
You're not changing the private property. Try this and see it fail:
A a = new A();
a.x = someOtherValue;
But the A class does allow you to read the property:
public Date getDate(){
return x;
}
And the Date class allows you to set its property:
d.setMonth(12);
No private member is being accessed outside of a class here. Date and A are two different classes.
This did not change x it is still pointing to the same object. What was changed is the object itself.
You are confusing reference with value.
The Date object referred to by x never changes and the field x is inaccessible from the sub class - ie the sub class can't assign a different Date object to x.
However, the getter allows you to access the object referred to by x, and (perhaps unexpectedly) Date objects are mutable - that is a Date's value can be changed. It's still the same Date object, but the instant in time it represents is different.
IMHO, the Date class is "broken"; it should be immutable.
The getDate() method is public. The getter method is public, that is you can now access the object and change its value. Date d and Date x are only reference to those objects not the actual objects.
sometime i have no choice to use mutable variable instead of immutable variables i know how many ways can create immutable vars but i wonder this way also correct its really convert mutable to immutable and i dont use concurrency or multithreading in my code just Curious?
public class Config implements FindIt {
....
private final class DateHolder{
private final Date dateContainDateObject;
DateHolder(String date) throws ParseException {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
dateContainDateObject = dateFormat.parse(date);
}
public Date getDate(){
return dateContainDateObject;
}
}
}
this is nested class and i use it like
private DateHolder holder;
and fill the holder variable in Config constructor class so holder variable are ThreadSafe ?
Date is a mutable object. Making it final means you can't change the reference to it, but you can still change what's at the reference (java.util.Date/Calendar nastiness strikes again, switch to the Java 8/Joda Time way if you can).
Don't expose any references to the Date member to the outside world. Instead make a defensive copy and pass that back instead. You might consider saving the time value as a final long instance member and only instantiating a Date when you need it.
can say is safe when you make class private and non-static, when you create form Config class you have only one DateHolder .
http://www.javapractices.com/topic/TopicAction.do?Id=29
why is static inner class singleton thread safe
http://www.javatpoint.com/how-to-create-immutable-class
A little side project I've been doing for fun involves subtracting the current date from a future date given by the user to return the days between them.
public int getDaysBetween(int date2)
{
//Subtract current date from future date (date2), leaving the number of days between them
int getDaysBetween = 0;
Calendar myCalendar = Calendar.getInstance();
myCalendar.get(Calendar.DAY_OF_YEAR);
getDaysBetween = date2-Calendar.DAY_OF_YEAR;
return getDaysBetween;
}
The method for doing this is non-static, as the date2 int changes. However, when I try to reference it in my main class...
//Figure out a non-static reference
int date2 = Integer.parseInt(JOptionPane.showInputDialog("Enter a day in the year ahead of today"));
message = "Days bewteen: " + Date.getDaysBetween(date2-Calendar.DAY_OF_YEAR);
JOptionPane.showMessageDialog(null, message);
I get the error that a non-static method cannot be referenced from a static context.
I am fairly new to Java, so it might seem easy to most of you guys, but I could use the help.
Thanks in advance!
The method for doing this is non-static, as the date2 int changes.
I think you've misunderstood the meaning of the static modifier.
Your method doesn't use any instance fields, and there's no reason to override it in subclasses, so it should be a static method.
date2 is a parameter, so each call to it can pass a different value. That doesn't depend on the instance you call the method on.
(As an aside, it's not really clear what your method is meant to achieve - are you really interested in the day of year? It's also likely that java.time or Joda Time would provide a better API for this. However, it's most important that you understand what static means... you might want to read the Java tutorial on class members.)
Your method appears to have intended to return date2 minus the current DAY_OF_YEAR (not minus the DAY_OF_YEAR constant). And if you make it static then you don't need an instance like,
public static int getDaysBetween(int date2) {
return date2 - Calendar.getInstance().get(Calendar.DAY_OF_YEAR);
}
Assuming this is your own Date class, then to make it non-static (or an instance level) you would need to call it on an instance like
message = "Days bewteen: " + new Date().getDaysBetween(date2);
But if it's static then you can use
message = "Days bewteen: " + Date.getDaysBetween(date2);
Finally, please don't name your class Date (the JRE includes at least two classes with that name java.sql.Date and java.util.Date).
The method is not static. This means you have to have an instance of the class to use the function. E.g:
Date date = new Date(); // Create an instance of the Date class
date.getDaysBetween(...); // The method call is related to the instance
What you are doing is trying to call the method as if it were static. A static method does not need an instance of the class. Instead it is a feature of a class itself. This if you want to perform a static method call like this:
Date.getDaysBetween(...);
You need to declare the method static:
public static int getDaysBetween(int date2)
The method for doing this is non-static, as the date2 int changes.
Static variable is one that is shared between all the instances of the Class.
Static method is a method that can be invoked without the need for creating and instance on the class.
Variables that cannot be changed are called constants and declared with a keyword "final".
When you declare your method, you can make it static by adding a "static" keyword in method declaration like this:
public static int getDaysBetween(int date2){}
Otherwise, you can keep your method non-static, but in this case, to invoke it, you would have to create an instance of a class and then call method on that instance:
message = "Days bewteen: " + new Date().getDaysBetween(date2);
I was wondering what the difference is between
public final type attribute_name;
and
private type attribute_name;
public type getA_name() {
return attribute_name;
}
Basically I want to make an attribute read-only, so it can't change after it has been initialized.
Do I make it public final, or do I make it private, and only make it accesible through a get method (without a set method)?
When it's not final but private, the class itself is able to change the value.
A final field MUST be set before the constructor exits. Once set, the reference cannot be modified (the value cannot be reassigned). Emphasis on the cannot be reassigned. This means that while the reference cannot change, the value itself can change.
This is legal:
final List<Integer> list = new List<Integer>();
list.add(5); // the value of list changes, but the reference doesn't
This is not:
final List<Integer> list = new List<Integer>();
list = new List<Integer>(); // may seem sort of redundant but the compiler won't allow it nonetheless
A private variable with a only getter can be reassigned internally by the class that holds it (but it's not visible externally so it cannot be reassigned outside the class holding it). Also, outside the class the reference is inaccessible so the variable cannot be modified except by the class holding it.
A final variable cannot be reassigned anywhere, but if it's public, another class can still access the reference and change the value of whatever object it points to.
If you don't want the variable to be reassigned after initialization as you described, use both final and private.
Use final for something like this:
public class User {
private final long registrationTimeMillis;
public User(/* various parameters probably would be here */) {
registrationTimeMillis = System.currentTimeMillis();
}
public long getRegistrationTimeMillis() {
return registrationTimeMillis;
}
}
We don't expect that a user's registration time will change, so it makes sense to not allow it to change after construction.
Use private with no setter for something like this:
public class VendingController() {
private int drinksStocked = 0;
private int drinksDispensed = 0;
public void dispenseDrink() {
drinksDispensed++;
}
public void stockDrinks(int numberOfDrinks) {
drinksStocked = getDrinksRemaining() + numberOfDrinks;
drinksDispensed = 0;
}
public int getDrinksRemaining() {
return drinksStocked - drinksDispensed;
}
}
We don't want the value of drinksDispensed to change except when dispenseDrink() or stockDrinks(int numberOfDrinks) is called. It still needs to be able to be reassigned by it's own class when the vending machine is refilled though, so we shouldn't make it final
With respect to using public final, generally in Java that's only done for constants and that static keyword is also included since constants shouldn't be dependent on an instance.
An example of when it makes sense to use public static final
public class UnitConversions {
public static final double CENTIMETERS_PER_INCH = 2.54;
}
It could then be used in a method as follows
public double convertFromCentimetersToInches(double centimeters) {
return centimeters / UnitConversions.CENTIMETERS_PER_INCH;
}
Best of luck OP and happy coding.
More reading on final fields
This depends on some factors.
If this is a real constant that is known before and will never change, then use final. In Java final fields can be initialized in the constructor as well, so if your value is known at construction time then you can use final too.
If this value gets set (once, multiple times) during runtime then use private + getter.
The final modifier allows a field to be assigned only once - it cannot be changed after that and it has to be set at during object construction (that is, before the constructor returns).
If you want to make the field read-only, use the principles of information hiding: make it private and provide a public getter that returns the field (or a copy of it for non-primitive types).
You should use public final only for true constants. Even if your field is immutable because of final it is often a good idea to still make it private.
The correct way is to think in the future. What would help you achieve your goals? Maybe later you would also like to give that variable a value. If I were you, I'd do this by creatin a get method and keeping the variable private.
Full documentation for final keyword : http://en.wikipedia.org/wiki/Final_(Java)
Depends on where you want to access it from. Public variables can be accessed from any class within the project and package where private can only be accessed from the class where the variable is.
The 'final' operator makes it permanent and read-only.
Let's assume that type is a reference to an object, not a primitive type.
public final type attribute_name means that attribute_name cannot be reassigned to refer to something else. But attribute_name can be used to call a method that changes its state.
In private type attribute_name, only methods within the class can call methods on attribute_name.
So if you want it to remain constant, use approach (2). Limit the public methods to ones that ultimately call methods on attribute_name that don't modify its state.
I've been using PMD to help spot potential problems in my Java code, and I've been finding its advice to be split between the useful, the idiosyncratic, and the "WTF?!".
One of the things it keeps telling me to do is to use the final keyword for literally every variable I can attach it to, including input parameters. For actual constants this seems sensible, but for other stuff it just strikes me as odd, possibly even a tad counterproductive.
Are there concrete advantages/disadvantages to hanging final on every variable declaration you possibly can?
"Every variable declaration you possibly can" sounds a bit extreme, but final is actually beneficial in many ways. Sometimes I wish that final was the default behavior, and required no keyword, but true "variables" required a variable modifier. Scala adopted something like this approach with its val and var keywords—using val (the final-like keyword) is strongly encouraged.
It is especially important to carefully consider whether each member variable is final, volatile, or neither, because the thread safety of the class depends on getting this right. Values assigned to final and volatile variables are always visible to other threads, without using a synchronized block.
For local variables, it's not as critical, but using final can help you reason about your code more clearly and avoid some mistakes. If you don't expect a value to change within a method, say so with final, and let the compiler find unnoticed violations of this expectation. I'm not aware of any that do currently, but it's easily conceivable that a JIT compiler could use this hint to improve performance too.
In practice, I don't declare local variables final whenever I could. I don't like the visual clutter and it seems cumbersome. But, that doesn't mean it's not something I should do.
A proposal has been made to add the var keyword to Java aimed at supporting type inference. But as part of that proposal, there have been a number of suggestions for additional ways of specifying local variable immutability. For example, one suggestion was to also add the key word val to declare an immutable variable with inferred type. Alternatively, some advocate using final and var together.
final tells the reader that the value or reference assigned first is the same at any time later.
As everything that CAN be final IS final in this scenario, a missing final tells the reader that the value will change later, and to take that into account.
This is a common idiom for tools like PMD. For example, below are the corresponding rules in Checkstyle. It's really a matter of style/preference and you could argue for both sides.
In my opinion, using final for method parameters and local variables (when applicable) is good style. The "design for extension" idiom is debatable.
http://checkstyle.sourceforge.net/config_misc.html#FinalParameters
http://checkstyle.sourceforge.net/config_design.html#DesignForExtension
http://checkstyle.sourceforge.net/config_coding.html#FinalLocalVariable
PMD also has option rules you can turn on that complains about final; it's an arbitrary rule.
If I'm doing a project where the API is being exported to another team - or to the world - leave the PMD rule as it stands. If you're just developing something that will forever and always be a closed API, disable the rule and save yourself some time.
Here are some reason why it may be beneficial to have almost everything tagged as final
Final Constants
public static class CircleToolsBetter {
public final static double PI = 3.141;
public double getCircleArea(final double radius) {
return (Math.pow(radius, 2) * PI);
}
}
This can be used then for other parts of your codes or accessed by other classes, that way if you would ever change the value you wouldn't have to change them one by one.
Final Variables
public static String someMethod(final String environmentKey) {
final String key = "env." + environmentKey;
System.out.println("Key is: " + key);
return (System.getProperty(key));
}
}
In this class, you build a scoped final variable that adds a prefix to the parameter environmentKey. In this case, the final variable is final only within the execution scope, which is different at each execution of the method. Each time the method is entered, the final is reconstructed. As soon as it is constructed, it cannot be changed during the scope of the method execution. This allows you to fix a variable in a method for the duration of the method. see below:
public class FinalVariables {
public final static void main(final String[] args) {
System.out.println("Note how the key variable is changed.");
someMethod("JAVA_HOME");
someMethod("ANT_HOME");
}
}
Final Constants
public double equation2Better(final double inputValue) {
final double K = 1.414;
final double X = 45.0;
double result = (((Math.pow(inputValue, 3.0d) * K) + X) * M);
double powInputValue = 0;
if (result > 360) {
powInputValue = X * Math.sin(result);
} else {
inputValue = K * Math.sin(result); // <= Compiler error
}
These are especially useful when you have really long lines of codes, and it will generate compiler error so you don't run into logic/business error when someone accidentally changes variables that shouldn't be changed.
Final Collections
The different case when we are talking about Collections, you need to set them as an unmodifiable.
public final static Set VALID_COLORS;
static {
Set temp = new HashSet( );
temp.add(Color.red);
temp.add(Color.orange);
temp.add(Color.yellow);
temp.add(Color.green);
temp.add(Color.blue);
temp.add(Color.decode("#4B0082")); // indigo
temp.add(Color.decode("#8A2BE2")); // violet
VALID_COLORS = Collections.unmodifiableSet(temp);
}
otherwise, if you don't set it as unmodifiable:
Set colors = Rainbow.VALID_COLORS;
colors.add(Color.black); // <= logic error but allowed by compiler
Final Classes and Final Methods cannot be extended or overwritten respectively.
EDIT: TO ADDRESS THE FINAL CLASS PROBLEM REGARDING ENCAPSULATION:
There are two ways to make a class final. The first is to use the keyword final in the class declaration:
public final class SomeClass {
// . . . Class contents
}
The second way to make a class final is to declare all of its constructors as private:
public class SomeClass {
public final static SOME_INSTANCE = new SomeClass(5);
private SomeClass(final int value) {
}
Marking it final saves you the trouble if finding out that it is actual a final, to demonstrate look at this Test class. looks public at first glance.
public class Test{
private Test(Class beanClass, Class stopClass, int flags)
throws Exception{
// . . . snip . . .
}
}
Unfortunately, since the only constructor of the class is private, it is impossible to extend this class. In the case of the Test class, there is no reason that the class should be final. The test class is a good example of how implicit final classes can cause problems.
So you should mark it final when you implicitly make a class final by making its constructor private.