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.

 Live Demo

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

Updated on: 29-Jun-2020

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements