0% completed
Using Member Variables
On This Page
- Defining Member Variables
Syntax:
Example:
- Updating Member Variables
Syntax:
Example:
- Accessing Member Variables
Syntax:
Example:
In Java, member variables (also known as fields) are variables declared within a class but outside any method, constructor, or block. These variables represent the properties or state of an object. By using member variables, you can store and manage data specific to each instance of a class.
1. Defining Member Variables
Member variables are declared inside a class and define the attributes or properties of that class. They can have different access modifiers (private, public, etc.) to control their visibility.
Syntax:
class ClassName { // AccessModifier dataType variableName; AccessModifier dataType variableName; }
Explanation:
- AccessModifier: Controls who can see or use the variable.
- dataType: The type of data the variable holds.
- variableName: The name of the variable, typically in camelCase.
Note: We will learn more about access modifiers in the Encapsulation chapter.
Example:
2. Updating Member Variables
Member variables can be updated by assigning new values to them using the object reference.
Syntax:
objectName.variableName = value;
Explanation:
- objectName: The reference to the object whose member variable you want to update.
- variableName: The name of the member variable you want to update.
- value: The new value you want to assign to the member variable. The value must be compatible with the variable's data type.
Example:
Explanation:
- We create a
Carobject. - We update its
brand,color, andyearmember variables. - Finally, we print them to confirm the updates.
3. Accessing Member Variables
After assigning values to member variables, we can retrieve them via the object reference.
Syntax:
dataType value = objectName.variableName;
Explanation:
- dataType: The type of data the variable holds.
- value: A new variable that will store the accessed value.
- objectName.variableName: Accesses the member variable
variableNamefrom the objectobjectName.
Example:
Explanation:
- We create an
Animalobject. - We assign values to
speciesandage. - We retrieve those values into local variables.
- We print them directly, and also call a method that uses the member variables.
Member variables are crucial for storing an object’s state. In this lesson, we learned how to define, update, and access these variables in Java. Through examples using Car and Animal classes, you can now handle member variables to manage object properties in your programs.
Reading Progress
0%
On This Page
- Defining Member Variables
Syntax:
Example:
- Updating Member Variables
Syntax:
Example:
- Accessing Member Variables
Syntax:
Example: