Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Using the Java program below on how to use wrapper classes to swap to objects, i

ID: 3591928 • 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

Here is the Main.java which has IntWrapper as an inner-class.

Code Snippet :

public class Main {
static class IntWrapper{
private Integer value;
public IntWrapper(Integer value){
this.value=value;
}
public Integer getValue(){
return value;
}
public void setValue(Integer i){
value=i;
}
public String toString(){
return value.toString();
}
}   

//Test function
static void increment(IntWrapper i){
Integer temp = i.getValue();
temp++;
i.setValue(temp);
}   
public static void main(String [] args){
IntWrapper intWrapper = new IntWrapper(10);
System.out.println(intWrapper);
increment(intWrapper);
System.out.println(intWrapper);
}   
  

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote