SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser
Chapter:
Object-oriented Design
Exercise:
Exercises
Question:21 | ISBN:9781118771334 | Edition: 6

Question

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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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
0 0

Discussions

Post the discussion to improve the above solution.