我们可以在Java中将对象作为参数传递吗?
是的,您可以在Java中将对象作为参数传递。请看以下示例:这里有一个名为Employee的类
示例
在下面的Java示例中,我们有一个带有两个实例变量名称和年龄的类,以及一个初始化这些变量的参数化构造函数。
我们有一个方法coypObject(),它接受当前类的一个对象,并使用该对象的变量初始化实例变量,然后将其返回。
在main方法中,我们实例化Student类并通过将其作为参数传递给coypObject()方法来进行复制。
import java.util.Scanner;
public class Student {
private String name;
private int age;
public Student(){
}
public Student(String name, int age){
this.name = name;
this.age = age;
}
public Student copyObject(Student std){
this.name = std.name;
this.age = std.age;
return std;
}
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().copyObject(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
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短