How to initiate a Java object with a variable?
<p>I am trying to initiate an object "rational number" that stores a numerator <code>p</code>, a denominator <code>q</code> and their ratio <code>r</code>. This code yields incorrect answer. </p>

<pre><code>class Rational { 
    int p, q;
    double ratio;

    public Rational(){
        this.p = 0;
        this.q = 1;
        this.ratio = this.p/(double)(this.q);
    }

    public static void main (String[]arg)  {
        Rational r1 = new Rational();

        r1.p = 1;  
        r1.q = 7;
        // r1.ratio = r1.p/(double)(r1.q);    //"this line"
        System.out.println (r1.p  + "/" + r1.q + " = " + r1.ratio) ;
    }
}
</code></pre>

<p>Uncommenting "this line" solves the problem. How to define object so that <code>this.r</code> is automatically updated each time <code>this.p</code> or <code>this.q</code> is changed?</p>