Object as parameters and Returning Objects

 

๐Ÿ”ท Using Objects as Parameters

✅ Why Use Objects as Parameters?

Passing an object as a parameter allows one class to use the data or behavior of another class.

This supports:

  • Code modularity

  • Encapsulation

  • Code reuse


๐Ÿงช Example:

class Student { String name; int age; Student(String n, int a) { name = n; age = a; } void display() { System.out.println(name + " is " + age + " years old."); } } class DisplayDetails { void printStudent(Student s) { s.display(); // calling method of Student class } } public class Main { public static void main(String[] args) { Student s1 = new Student("Alice", 20); DisplayDetails d = new DisplayDetails(); d.printStudent(s1); // Passing object as parameter } }

๐Ÿ”„ Output:

Alice is 20 years old.

๐Ÿ”ท Returning Objects from Methods

✅ What is it?

In Java, a method can return an object instead of a primitive type. This allows chaining of object operations and building modular code.


๐Ÿงช Example:

java
class Rectangle { int length, width; Rectangle(int l, int w) { length = l; width = w; } Rectangle larger(Rectangle r2) { int area1 = this.length * this.width; int area2 = r2.length * r2.width; return (area1 > area2) ? this : r2; // returning the larger rectangle } void display() { System.out.println("Length: " + length + ", Width: " + width); } } public class Main { public static void main(String[] args) { Rectangle r1 = new Rectangle(4, 5); Rectangle r2 = new Rectangle(3, 6); Rectangle big = r1.larger(r2); // method returns an object System.out.print("Larger Rectangle: "); big.display(); } }

๐Ÿ”„ Output:

Larger Rectangle: Length: 4, Width: 5

๐Ÿง  Summary

ConceptDescription


Objects as Parameters        Enables reuse of data and methods of an object in another class
Returning Objects        Allows method to send back an object for further operations

Comments

Popular posts from this blog

Object Oriented Programming PBCST304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Introduction to Java Programming

Java Compiler and Java Virtual Machine