0
class B {
    int vf;
    static int sf;
    B(int i){
        vf = i;
        sf = i+1;
    }
}

class C extends B{
    int vf;
    static int sf;
    C (int i) {
        super(i+20);
        vf = i;
        sf = i+2;
    }
}

class D extends C {
    int vf;
    D(int i) {
        super(i+40);
        vf = i;
        sf = i+4;
    }

    static void print(int a, int b) {
        System.out.println(a + " " + b);
    }
    static void print(int a, int b, int c) {
        System.out.println(a + " " + b + " " + c);
    }

    public static void main(String[] args) {
        C c1 = new C(100); // c1 has type C; object has class C
        B b1 = c1; // b1 has type B; object has class C
        print(C.sf, B.sf); // 102 121
        print(c1.sf, b1.sf); // 102 121
        print(c1.vf, b1.vf); // 100 120

        System.out.println("===================");

        C c2  = new C(200);
        B b2 = c2;
        print(c2.sf, b2.sf); // 202 221 
        print(c2.vf, b2.vf); // 200 220
        print(c1.sf, b1.sf); // 202 221 
        print(C.sf, B.sf); //202 221

        System.out.println("===================");

        D d3 = new D(300);
        C c3 = d3;
        B b3 = d3;
        **print(D.sf, C.sf, B.sf); //304 342 361
        print(d3.sf, c3.sf, b3.sf); //304 342 361**
        print(d3.vf, c3.vf, b3.vf); //300 340 360
    }
}

/** Question) Hi, I am a java beginner and not even sure if this is a appropriate question to ask here, but I don't understand why the print(D.sf, C.sf, B.sf); gives 304 for C.sf. I thought it would be 342.

Thank you for your help in advance. */

narirock
  • 61
  • 4
  • Hello and welcome to StackOverflow. Please take some time to read the help page, especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). And more importantly, please read [the Stack Overflow question checklist](http://meta.stackexchange.com/q/156810/204922). You might also want to learn about [Minimal, Complete, and Verifiable Examples](http://stackoverflow.com/help/mcve). – Clijsters Dec 06 '17 at 08:20
  • `c3` is declare as a `C`, so it return `C.sf`, that value is set last with `sf = i+4;` in `D` (Because `D` don't have his own `sf` variable to shadow the `C.sf`, it directly access `C.sf`. Please reduce the scope of this question to understand what you don't understand, is it the overriding/shadowing or the statement order ? – AxelH Dec 06 '17 at 08:31
  • @AxelH Thank you for the answer and the suggestion!! Huge help :) – narirock Dec 06 '17 at 08:41

0 Answers0