public class Car { private String color; private int numWheels; public Car(Strin
ID: 638265 • Letter: P
Question
public class Car {
private String color;
private int numWheels;
public Car(String color, int numWheels) {
this.color = color;
this.numWheels = numWheels;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getNumWheels() {
return numWheels;
}
public void setNumWheels(int numWheels) {
this.numWheels = numWheels;
}
}
public class CarTest {
public static void main(String[] argvs) {
CarTest carTest = new CarTest();
carTest.runDemo();
}
public void runDemo() {
Car c = new Car("blue", 4);
changeColor(c, "red");
System.out.println(c.getColor());
}
public void changeColor(Car car, String newColor) {
car.setColor(newColor);
}
}
What is output when the CarTest application is run? Why?
Explanation / Answer
Output
======================
red
Explanation
=============================
1. Car c = new Car("blue", 4);
This statement creates car object with name c and having its properties as
color is blue and number of wheels are 4
2. changeColor(c, "red");
This statmenet calls the changeColor method where changeColor method takes class object
and color to be changed as parameters.
Here, c is the car object and color to be changed is red.
Inside changeColor(Car car, String newColor) method
=======================================================
car.setColor(newColor);
This statement will set the newColor red to the car object
3. System.out.println(c.getColor());
Hence the new car color is red is printed on the console.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.