public class Point {
private double x;
private double y;
Point (double x, double y)
{ this.x = x; this.y = y; }
double getX() { return x; }
double getY() { return y; } }
Are the objects in the above class immutable? Explain.
I am getting confused because
There r no setters so nothing can modify the objects
BUT
there is no final variable or final class which it should contain.
If the class gets extended, it could add extra fields that are not immutable, or the methods could be overridden to return a different value each time. Doesnt this make the class not immutable?
If the class gets extended, ... the methods could be overridden to return a different value each time. Doesn't this make the class not immutable?
Your question is subtle. If some class MutPoint extends Point and overrides the getX() and getY() methods to return non-constant values, that doesn't change the Point class itself. Instances of Point sill will be effectively immutable, but a caller would be allowed to pass MutPoint objects to your methods that expect Point arguments. What happens then? Depends on how you write your code. It could be that your code would behave badly if the caller gave you a Point-like object, and then subsequently changed its "value".
If your code that uses Point objects requires them to never change, then you might want to declare the whole class final
public final class Point { ... }
That way, your client will not be allowed to override the class, and will not be allowed to call your methods with anything other than an actual Point instance.
Yes, they are immutable. You can read about it here
http://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html
Yes, because you can't accsess to the data member and you don't have method that change your data members
Related
Non-static final variables can be assigned a value only once.
But why this assignment can happen only either within a declaration or in the constructor?
A final variable is defined to be immutable i.e., the value assigned to it will be the one and only for that variable x. As one can read from the JLS(§4.12.4.)
A variable can be declared final. A final variable may only be
assigned to once.
Now the constructor is just like any other method, except that it is the one that gets executed first when an object (non-static) is created from the class.
Hence, final variables can be assigned through constructors.
For example take the following code:
public class Test {
public final int x;
public Test(int x) {
this.x = x;
}
}
Compiler accepts this invocation because it is guaranteed that for that particular object its class's constructor gets invoked first and doesn't invoked again (i.e. constructor gets invoked one and only one time during the entire lifetime of object.)
However following code throws error: Non-static field 'x' cannot be referenced from a static context
public class Test {
public final int x;
static {
x = 5;
}
public Test(int x) {
this.x = x;
}
}
Since x is not a static field, it cannot be initiated within a static block.
This code would also throw error: Cannot assign a value to final variable 'x'
public class Test {
public final int x;
public Test(int x) {
this.x = x;
}
public void setX(int x) {
this.x = x;
}
}
That is because it is not guaranteed for this object, that the method setX would run first and only once. The programmer could call this method multiple times. Hence, the compiler throws an error.
So there is no way to make a variable "initializable" only once (e.g.,
a setter would block if variable was already assigned before) solely
with java syntax? I thought final might work this way but now I see
it's not.
For your question, you could simply make a variable private and add the condition to the setter method to add value only if variable is null.
For example:
public class Test {
private Integer x;
public Test() {
}
public Test(int x) {
this.x = x;
}
public void setX(int x) {
if (null == this.x) this.x = x;
}
public static void main(String[] args) {
Test y = new Test(5);
System.out.println(y.x);
y.setX(20);
System.out.println(y.x);
}
}
This is not thread safe by the way. I just added a simple example.
What does the keyword final mean in Java?
When used in a class declaration, it means that the class cannot be extended.
When used in a method, it means that the method cannot be overridden.
When used in a method parameter, it means the value of such parameter cannot be changed inside the method. (local constant)
When used in a class field ("variable), it means that it is a global constant.
Values for constants must be resolved at compile time. And, as the word implies, constants fields cannot change value. Therefore, the compiler does not allow the value to be set from a setter (mutator) method.
Contrary to what many believe, for a field to be constant, it does not have to be declared static and final. That said, since the value of a constant cannot be changed, each class instance will share the same value. Therefore, explicitly making them static reenforces this notion.
There is a fifth use of the keyword final and this is when used when local variables are declared. This is a more lengthy explanation.
What happens when you compile code?
I updated my answer because I think part of the problem is that some developers don't quite understand what happens when the code is compiled. As I mentioned before, constant values are resolved at COMPILE TIME. To understand this concept, consider the following example:
public class MyClass {
private final double PI = 3.14159;
// rest of class left out intentionally
}
If I compile this class on my laptop and then I deploy the code to some remote server, how does the server know that the global constant field PI has an assigned value of 3.14159? This is because when I compile this code, this value gets packaged with the byte code. The class constructor doesn't come into play at all in this case. HOWEVER, if the constant field is initialized to its DEFAULT value, then permanent (constant) value may be assigned via the constructor
public class MyClass {
private final double PI; // default value of 0.0
public MyClass(double value) {
PI = value;
}
// rest of code omitted intentionally
}
Here's where declaring a constant as static makes a difference. If a constant is also static, you can't do the above because calling a constructor implies that you can have multiple instances of MyClass and each instance could set a different value. This is clearly a violation of what a static member is. So, if you MUST declare a field as both static and final, understand that you cannot assign a value using this second approach. Only the first one I showed is allowed.
Final Stop's a Variable’s Reassignment
a short simple answer:
Use the keyword final when you want the compiler to prevent a variable from being re-assigned to a different object.
Whether the variable is a static variable, member variable, local variable, or argument/parameter variable, the effect is entirely the same.
Hope this helps friend =)
#StaySafe
Let's say i have an Object:
class Obj o{
public int x;
public int y;
}
and a thread calls the method:
update(Obj o, int x, int y){
o.x = x;
o.y = y;
}
How can I prevent that other threads have access to the fields of this object during the execution of 'update' and wait until the method is finished to read the data?
You will need to make the members of the Obj class private so you have control over their access. Then, move the update() method inside the class and declare it synchronized. Finally, create getX() and getY() methods inside the class to get the values and declare them synchronized as well.
Making all these methods members of the class and synchronizing them will ensure that they can't be run by different threads at the "same time".
I have trouble understanding why double xx and yy are put final in the constructor. Why don't I just put them double xx and double yy. Why
do they have to be final? I guess the whole purpose of this is
creating an immutable object.
public class Point {
private final double x, y;
private double distance;
public Point(final double xx, final double yy) {
this.x = xx;
this.y = yy;
this.distance = -1;
}
}
There is no need for these parameters to be final.
There are two reasons to make parameters final:
To make use of them in an inner class declared in that function;
To prevent their values from being changed accidentally.
Clearly (1) doesn't apply.
(2) isn't necessary because it's such simple code, and you can see that it's not changing the parameters.
There is a school of thought which says that all parameters and local variables should be declared final as a matter of course, as it makes it easier to reason about the code, in the same way that using immutable types makes it easier to reason about code using them.
There is another school of thought which says that adding final everywhere is just unnecessary noise, and, if you are writing methods where you can't tell if the value is changing, your methods are too long.
Largely, making parameters and local variables final comes down to personal/team preference.
Declaring x and y variables as final solves the purpose (i.e. The value must not be changed later). There is no point in declaring the constructor's parameters as final.
public class NotActuallyImmutable {
private final int x;
public NotActuallyImmutable(int x) {
this.x = x;// line 1
}
public int getX() {
return x;
}
}
public class Mutable extends NotActuallyImmutable {
private int x = 123;
public Mutable(int x) {
super(x);
}
public int getX() {
return x++;
}
}
now in my main class
NotActuallyImmutable n = new Mutable(42); // line2
int x = n.getX();
System.out.println("x is"+x);
I am expecting the output as 42 but it return the output as 123. I am expecting 42 because at line 2 I am making object of class Mutable and then at line 1 I am setting value as 42. so when i do n.getX() I should get the this latest value not the default 123. I know Ii am missing something but not able to figure out the logic behind it?
The problem is that the field x in Mutable and the field x in class NotActuallyImmutable are not the same. The x that is returned by getX() is the one in Mutable (because the getX() that is invoked is Mutable.getX(), not NotActuallyImmutable.getX()).
Note that if you removed the instance field from Mutable, then you would have a compiler error because NotActuallyImmutable.x is private to NotActuallyImmutable and not accessible to any code in Mutable.
If you made NotActuallyImmutable.x a protected field, then Mutable.x would shadow it and you would still have the same behavior. If you removed Mutable.x in this case, you would still have a compiler error because you were trying to increment a final field.
If you remove Mutable.getX(), then the x that would be returned by getX() would be NotActuallyImmutable.x, despite there being another field of the same name in Mutable.
The private int x in Mutable and the private int x in NotActuallyImmutable are completely different fields that just have the same name.
This isn't a problem for the compiler because you can't access a private field from another class. So as far as the compiler is concerned, when you define Mutable, the x in NotActuallyImmutable is invisible and might as well not exist.
It is of course confusing for the programmer. If you rename one of the fields to y (and the getter method to getY) the behaviour seems much more intuitive.
NotActuallyImmutable n = new Mutable(42); // line2
This means you have an object of type NotActuallyImmutable but the instance of created object is Mutable.
so in this code your dealing with Mutable object which will return 123. as the number you passed is saved in NotActuallyImmutable not in Mutable,
n has two different x values which are visible in different contexts, the parent class's private member variable and the child class's private member variable.
NotActuallyImmutable n = new Mutable(42); // line2
Creates a new Mutable. Executes parent(x) which sets the parent class's x to 42.
int x = n.getX();
n is a Mutable instance so this calls Mutable's getX() which returns Mutable's value for x (123) rather than the parent's.
I agree with Nice explanations given in above answers. But to to just brief the final understanding. As i am doing new Mutable(42).getX(), jvm first will look in Mutable object to get the value of X not inside NotActuallyImmutable. If i remove getX() method from Mutable , i get the expected(as per my expectation) value i.e 42.
This example gets messy becoz variable name i.e X is same in parent and child class but good for understanding concept
Though I'm trying to understand why "this" is needed, I'm very confused about its purpose. For instance, I coded the following:
public static void main (String args[])
{
SandboxClass1 temp = new SandboxClass1(1,2,3);
System.out.println(temp.getX());
System.out.println(temp.getY());
System.out.println(temp.getZ());
System.out.println("----------------------------");
SandboxClass1 temp2 = new SandboxClass1(4,5,6);
System.out.println(temp2.getX());
System.out.println(temp2.getY());
System.out.println(temp2.getZ());
}
public class SandboxClass1
{
private int x = 1;
private int y = 1;
private int z = 0;
public SandboxClass1(int x, int y, int zz)
{
this.x = x;
this.y = y;
z = zz;
}
public int getX()
{
return(this.x);
}
public int getY()
{
return(this.y);
}
public int getZ()
{
return(this.z);
}
}
Why do I need to code "this.z = zz"
when I could just as well write, "z = zz"?
You don't, in this case. It's only required when you must eliminate ambiguity, like when parameters and instance variables share a name.
Some people prefer to use "this" to remove conceptual ambiguity and explicitly state that the code references an instance variable.
(On a side note, the parentheses around the return values are unnecessary and a bit noisy, IMO.)
In your SandboxClass1 constructor, you have two pairs of variables each called x and y. There's the x and y declared on the object itself ("private int x = 1"), and the separate x and y that are parameters to the constructor ("int x").
The local (parameter) variable shadows the class variable. So if in the constructor you just did
x = x;
the assignment would have no effect.
The keyword this is a reference to the object that the method/constructor was called on. In the statement
this.x = x;
you're using it to assign to the other x at class level. By qualifying the name, you can tell them apart.
It's not necessary to use this with the z/zz assignment because they have different names.
It's also not necessary in the getX/Y/Z methods because there are no local variables in those methods shadowing the relevant class variables. It does no harm though.
In the SandboxClass1 constructor two of the parameters (x and y) hide class variables because they are the same name. If you want to assign the class variable x to any value while in the code>SandboxClass1 constructor, you must address it using this.x to tell the compiler that "I want to assign the class scope variable named x, and not the method scope variable named x". The same applies to y.
Since the parameter z does not hide the class scope variable named zz you do not need to tell the compiler the scope of the zz variable, the class scope zz is the only recognized variable so that is the one that gets assigned.
It has the same effect. this is needed if there is a local variable which overrides a field of the class; then you get the local variable and not the class field.
An additional advantage you can indicate the variables better. If there is a this; it's a field; local variable otherwise.
the keyword this is used to refer to an attribute that is in the class. The keyword this was created to distinguish between class attributes and method parameters. like this:
public class human
{
public void setName(String name)
{
// the first name is a reference to the class attribute name
this.name = name;
// the second name is a reference to the method parameter name
}
// definition of the class attribute name
private String name;
}
when you use the keyword this it refers to the name variable inside the class heres an example where you don't need to use this:
public class Human
{
public void setName(String myName)
{
name = myName
}
private String name;
}
see now there is only 1 variable named name and there is only one variable named myName. In the other example there was 2 variables named name. One was a class attribute and one was a method parameter.
'this' operator just refines that property/field belongs to class you're working in. It's useful whe you have, for example, two variables with the same name:
this.zz = zz;
Unlike, say, Objective-C, "this" is optional when the method or variable is local, and there is no other conflicting use of the same name.
It comes in handy in conflicting-name cases, though, such as in methods that set instance variables such as void setOnionCount(int onionCount) where you would like to use "onionCount" for the formal parameter but still have "onionCount" as the instance variable name. In such a case you can do this.onionCount = onionCount; and everyone is happy (except, I suppose, those in the Peanut Gallery who'll object to this technique).
"this" is also absolutely necessary in cases where you need to pass a reference to the current object to some other class, of course.
hey this is use to provide reference of invoking object. That i.e say suppose ur class is box then if you want to provide it's object then you can provide it within the class box using this keyword.
class Box {
int x;
public Box(int x){
this.x = x;
}
}
here in this case if your object is ob (i.e Box ob = new Box(1)) then the reference it will be passed to the itself.
Note: you cannot use this keyword outside of the class. If you use so then it will give reference of another class.
for complete detail on this keyword refer following link
http://download.oracle.com/javase/tutorial/java/javaOO/thiskey.html