Write a program that consists of three classes, A, B, and C, such that B extends A and that C extends B. Each class should define an instance variable named “x” (that is, each has its own variable named x). Describe a way for a method in C to access and set A’s version of x to a given value, without changing B or C’s version.
Program code:
class A {
protected int x;
public void setX(int value) {
x = value;
}
}
class B extends A {
// Inherits the instance variable x from class A
}
class C extends B {
public void accessAndSetAX(A obj, int value) {
// Access and set A's version of x through the object of type A
obj.setX(value);
}
}
public class Main {
public static void main(String[] args) {
C c = new C();
A a = new A();
System.out.println("Before setting A's x:");
System.out.println("A's x: " + a.x); // Prints the initial value of A's x
c.accessAndSetAX(a, 42); // Access and set A's x through C
System.out.println("After setting A's x:");
System.out.println("A's x: " + a.x); // Prints the updated value of A's x
}
}
OUTPUT OF THE PROGRAM CODE:
Before setting A's x:
A's x: 0
After setting A's x:
A's x: 42