Home> Java> javaTutorial> body text

Discussion on Java Reference and Copy Instances

WBOY
Release: 2023-04-25 22:10:13
forward
774 people have browsed it

1. Concept

Reference copy is our commonly used object assignment. This method will not generate a new object, but will onlyadd a new object to the original object. Object reference, the two references still point to the same object.

2. Form

The default assignment method of Java objects is reference copying. For example, the process of object assignment in the following code is reference copying:

User user1 = new User(); User user2 = user1;
Copy after login

3. Example

class Son { String name; int age; public Son(String name, int age) { this.name = name; this.age = age; } } public class test { public static void main(String[] args) { Son s1 = new Son("son1", 12); Son s2 = s1; s1.age = 22; System.out.println(s1); System.out.println(s2); System.out.println("s1的age:" + s1.age); System.out.println("s2的age:" + s2.age); System.out.println("s1==s2" + (s1 == s2));//相等 } }
Copy after login

The output result is:

Son@135fbaa4 Son@135fbaa4 s1的age:22 s2的age:22 True
Copy after login

The above is the detailed content of Discussion on Java Reference and Copy Instances. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!