 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can we pass objects as an argument in Java?
Yes, you can pass objects as arguments in Java. Consider the following example: Here we have a class with name Employee
Example
In the following Java example, we a have a class with two instance variables name and age and a parameterized constructor initializing these variables.
We have a method coypObject() which accepts an object of the current class and initializes the instance variables with the variables of this object and returns it.
In the main method we are instantiating the Student class and making a copy by passing it as an argument to the coypObject() method.
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();    } }  Output
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
Advertisements
 