Class
Definition
Example
Member Variables
There are several kinds of variables:
- Member variables in a class—these are called fields.
- Variables in a method or block of code—these are called local variables.
- Variables in method declarations—these are called parameters.
Access Modifiers
The first (left-most) modifier used lets you control what other classes have access to a member field. For the moment, consider only public
and private
. Other access modifiers will be discussed later.
public
modifier—the field is accessible from all classes.private
modifier—the field is accessible only within its own class.
Example
Methods
Method Signature
The method's name and the parameter types comprise the method signature.
Overloading Methods
Constructors
Constructor declarations look like method declarations—except that they use the name of the class and have no return type.
Constructors can be:
- Default constructor: if you did not define a constructor, the compiler will create a default one with no parameters.
- No-argument constructor: a constructor without any parameters.
- Parameterized constructor: a constructor accepts parameters.
- Copy constructor: a constructor accepts an object with the same type as its parameter.
Passing Parameters
By Reference or By Value?
{% hint style="warning" %} Java always passes arguments by value. {% endhint %}
Definitions
Reference
Here, o
is a reference, and its value is an address.
Value
The literal value.
Here, i
is a primitive type not a reference, and its value is 1
.
Passing Primitive Data Type Arguments
Primitive arguments, such as an int
or a double
, are passed into methods by value.
When you run this program, the output is:
Passing Reference Data Type Arguments
Reference data type parameters, such as objects, are also passed into methods by value.
info
Recall that value is an address. 🙋♂
https://stackoverflow.com/questions/7893492/is-java-really-passing-objects-by-value/7893495#7893495
https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html