In Java, a reference variable holds the memory address of an object. When you create an object, the Java Virtual Machine (JVM) allocates memory for its data and methods. The reference variable stores this memory address, allowing you to access and manipulate the object.

Here's an example illustrating this relationship:

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void sayHello() {
        System.out.println('Hello, my name is ' + name + ' and I'm ' + age + ' years old.');
    }
}

public class Main {
    public static void main(String[] args) {
        // Create a Person object and assign to a reference variable
        Person john = new Person('John', 30);

        // Call the sayHello() method using the reference variable
        john.sayHello();
    }
}

In this example, the Person class has name, age fields and a sayHello() method. In the Main class, a Person object is created and assigned to the john reference variable. Using the dot notation (john.sayHello()), we call the sayHello() method on the john object, which prints 'Hello, my name is John and I'm 30 years old.'

In essence, the reference variable (john) holds the memory address of the Person object, enabling access and manipulation of its data and methods.

Java Reference Variables and Objects Explained with Example

原文地址: https://www.cveoy.top/t/topic/mZ6k 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录