Accessing Instance Members
Accessing Instance Variables
To access an instance variable from outside the class, you can use the dot (.) operator. The syntax is as follows:
objectReference.instanceVariableName
Here, objectReference is a reference to the object, and instanceVariableName is the name of the instance variable you want to access.
For example, let's consider the Person class we defined earlier:
class Person {
String name;
int age;
String address;
public void introduce() {
System.out.println("My name is " + this.name + ", I am " + this.age + " years old, and I live at " + this.address + ".");
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.name = "John Doe";
person.age = 30;
person.address = "123 Main St, Anytown USA";
person.introduce();
}
}
In the Main class, we create a Person object and then access its instance variables using the dot operator (person.name, person.age, person.address).
Accessing Instance Methods
To call an instance method, you need to have a reference to the object on which the method is to be called. The syntax is as follows:
objectReference.methodName(arguments)
Here, objectReference is a reference to the object, methodName is the name of the instance method, and arguments are the input parameters (if any) for the method.
Continuing the example from the previous section:
class Person {
String name;
int age;
String address;
public void introduce() {
System.out.println("My name is " + this.name + ", I am " + this.age + " years old, and I live at " + this.address + ".");
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.name = "John Doe";
person.age = 30;
person.address = "123 Main St, Anytown USA";
person.introduce();
}
}
In the Main class, we call the introduce() instance method on the person object using the dot operator (person.introduce()).
By understanding how to access instance variables and methods, you can effectively work with objects and their state in your Java programs.
classDiagram
class Person {
+String name
+int age
+String address
+introduce()
}
class Main {
+main(String[])
}
Main --> Person