Given the class ‘ReadOnly’ with the following behavior : A (protected) integer instance variable named ‘val’. A constructor that accepts an integer and assigns the value of the parameter to the instance variable ‘val’.

Given the class ‘ReadOnly’ with the following behavior : A (protected) integer instance variable named ‘val’. A constructor that accepts an integer and assigns the value of the parameter to the instance variable ‘val’.

LANGUAGE: JAVA

CHALLENGE:

Given the class ‘ReadOnly’ with the following behavior :
A (protected) integer instance variable named ‘val’.
A constructor that accepts an integer and assigns the value of the parameter to the instance variable ‘val’.
A method name ‘getVal’ that returns the value of ‘val’.

Write a subclass named ‘ReadWrite’ with the following additional behavior :
Any necessary constructors.
a method named ‘setVal’ that accepts an integer parameter and assigns it the the ‘val’ instance variable.
a method ‘isDirty’ that returns true if the setVal method was used to override the value of the ‘val’ variable.

SOLUTION:

public class ReadWrite extends ReadOnly {
    public ReadWrite(int initialValue){
        super(initialValue);
    }
    private boolean modified = false;
    public void setVal(int x) {
        val = x;
        modified = true;
    }
    public boolean isDirty() {
        return modified;
    }
}

Add comment