Using the Java program below on how to use wrapper classes to swap to objects, i
ID: 3591939 • Letter: U
Question
Using the Java program below on how to use wrapper classes to swap to objects, implement a passing by reference of the parameters in the function swap. For this purpose define the class IntWrapper as a wrapper of an integer. Define the class IntWrapper as an inner class on the class Main.
Please provide the main.java and output
// A Java program to demonstrate that we can use wrapper
// classes to swap to objects
// A car with model and no.
class Car
{
int model, no;
// Constructor
Car(int model, int no)
{
this.model = model;
this.no = no;
}
// Utility method to print object details
void print()
{
System.out.println("no = " + no +
", model = " + model);
}
}
// A Wrapper over class that is used for swapping
class CarWrapper
{
Car c;
// Constructor
CarWrapper(Car c) {this.c = c;}
}
// A Class that use Car and swaps objects of Car
// using CarWrapper
class Main
{
// This method swaps car objects in wrappers
// cw1 and cw2
public static void swap(CarWrapper cw1,
CarWrapper cw2)
{
Car temp = cw1.c;
cw1.c = cw2.c;
cw2.c = temp;
}
// Driver method
public static void main(String[] args)
{
Car c1 = new Car(101, 1);
Car c2 = new Car(202, 2);
CarWrapper cw1 = new CarWrapper(c1);
CarWrapper cw2 = new CarWrapper(c2);
swap(cw1, cw2);
cw1.c.print();
cw2.c.print();
}
}
Explanation / Answer
All this code inside main class:
class IntWrapper
{
int i;
// Constructor
IntWrapper(int i) {this.i = i;}
}
Correspoding swap function is :
public static void swap(IntWrapper iw1, IntWrapper iw2)
{
int temp = iw1.i;
iw1.i = iw2.i;
iw2.i = temp;
}
Calling swap :
swap(iw1,iw2);
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.