First of all, you need to read about what "pass by reference" really means. (For example, here.) Passing semantics refer to what happens to arguments in a procedure/method/subroutine/function call. In your example, there is no "passing" going on at all when you are assigning to the x
field.
So your
In Java are object attributes passed by reference to other classes
is a meaningless and/or irrelevant question. (But the plain answer is that Java does not support "pass by reference". Period.)
As for what I think you are trying to ask, lets start with some facts:
The Field
class declares x
as an instance field.
Each instance of First
has its own "copy" of the x
field.
The x
field is part of one and only one instance. It is not shared with any other First
instance.
This is irrespective of the declared type of x
... modulo that a field whose declared type is a reference type will contain a reference to an object rather than the object itself. (But int
is not a reference type.)
The new First()
expression creates a new instance of the First
class that is distinct from all other (past, present or future) instances of First
and returns its reference.
So, in this code:
First f1 = new First();
First f2 = new First();
f1.x = 2;
System.out.println(f2.x); // prints 1.
We have two instances of First
that f1
and f2
refer to (point at) distinct First
instances. If you change the x
field of one instance does not change the x
field of the other intance. They are different fields.
However, if you had declared x
as static
in First
, then x
is no longer a distinct field for each First
instance. It is now a shared by all instances of First
.
As an addendum, how would one change the default value of x in the First class such that any new instance made afterwards would have a difference value of x to start?
Firstly int x = 1;
in First
is not defining a "default" value in the sense that Java uses that term. It is actually an initialization. (A default value is what you see if you DON'T have an initialization.)
If you wanted to implement application specific default value that is common to all instances of First
and that can be changed retrospectively, you need to implement it in Java code. Maybe something like this:
public class First {
static int defaultX = 1;
private int x;
private boolean xSet = false;
public int getX() {
return xSet ? x : defaultX;
}
public void setX(int x) {
this.x = x;
this.xSet = true;
}
}
Note that in order to implement the defaulting behavior we want, we have to hide the x
field (make it private) and implement the desired behavior in the getter and setter methods.