I am new to programming. My code are listed below.

public abstract class Mark {
  private double mark;

  public double getMark() {
    return Mark;
  }

  public void setMark(double mark) {
    this.mark = mark;
  }

  public abstract void calculateMark(double x, double y, double z);
}
public class Test extends Mark {
  public void calculateMark(double test1, double test2, double test3) {
    setMark(test1 * 0.5 + test2 * 0.3 + test3 * 0.2);
  }
}
public class TestMark {
  public static void main(String[] args) {
    Mark test = new Test();

    test.calculateMark(50, 70, 89);
    test.setMark(90);
    System.out.println("Total = " + test.getMark());
  }
}

In class TestMark, I use the method setMark() to change the mark to 90.
How can I avoid the change of the mark through setMark() method?

Recommended Answers

All 2 Replies

If you don't want anyone to be able to change the mark just don't have a setMark method. If you want to be able to do it yourself, but not allow anyone else, make the method private.

or, if you mean that it may only be changed if it has a certain value, for instance, it has to be a positive value:

public void setMark(double mark) {
    if ( mark >= 0)
    this.mark = mark;
  }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.