java的复制构造函数_什么是Java中的复制构造函数?

通常,复制构造函数是通过使用先前已创建的相同类的对象初始化对象来创建对象的构造函数。

Java支持复制构造函数,但与C语言不同,Java没有提供您需要自己定义的显式复制构造函数。

写一个拷贝构造函数

通常,为了初始化类的实例变量的值(一种方式),我们创建一个参数化的构造函数,接受所有实例变量的值,并使用给定的值对其进行初始化。int name;

int age;

public Student(String name, int age){

this.name = name;

this.age = age;

}

但是,在复制构造函数中,接受当前类的对象,并使用获取的对象中的值初始化实例变量的值。public Student(Student std){

this.name = std.name;

this.age = std.age;

}

然后,如果您创建了一个对象并通过传递对象来调用副本构造函数,则将获得您之前创建的对象的副本。Student std = new Student("nameValue", ageValue);

Student copyOfStd = new Student(std);

示例

以下是演示Java中的副本构造函数的示例。import java.util.Scanner;

public class Student {

private String name;

private int age;

public Student(String name, int age){

this.name = name;

this.age = age;

}

public Student(Student std){

this.name = std.name;

this.age = std.age;

}

public void displayData(){

System.out.println("Name : "+this.name);

System.out.println("Age : "+this.age);

}

public static void main(String[] args) {

Scanner sc =new Scanner(System.in);

System.out.println("Enter your name ");

String name = sc.next();

System.out.println("Enter your age ");

int age = sc.nextInt();

Student std = new Student(name, age);

System.out.println("Contents of the original object");

std.displayData();

System.out.println("Contents of the copied object");

Student copyOfStd = new Student(std);

copyOfStd.displayData();

}

}

输出结果Enter your name

Krishna

Enter your age

20

Contents of the original object

Name : Krishna

Age : 20

Contents of the copied object

Name : Krishna

Age : 20

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值