Search code examples
javaabstract-classextend

Java procedures of extending abstract class


I am not clear about the procedure of extending a class. Given the following piece of code, why the output is 32?

class Rts {
    public static void main(String[] args) {
        System.out.println(zorg(new RtsC()));
    }

    static int zorg(RtsA x) {
        return x.f()*10 + x.a;
    }
}

abstract class RtsA {
    int a = 2;
    int f() { return a; }
}

class RtsB extends RtsA {
    int a = 3;
    int f() { return a; }
}

class RtsC extends RtsB {
    int a = 4;
}

Solution

  • First off, fields aren't overridden, so all this is equivalent to

    public class Rts {
        public static void main(String[] args) {
            System.out.println(zorg(new RtsC()));
        }
        static int zorg(RtsA x) {
            return x.f()*10 + x.a;
        } 
    }
    
    abstract class RtsA {
      int a = 2;
      int f() { return a; }
    }
    class RtsB extends RtsA {
      int b = 3;
      int f() { return b; }
    }
    class RtsC extends RtsB {
      int c = 4;
    }
    

    The implementation of f() for an object of type RtsC comes from RtsB, since that is the lowest-level class that overrides f(), so its implementation is used, and that returns b, which is 3. That's multiplied by 10, and then added to the a from RtsA, since zorg only knows that x is of type RtsA, so that field is used. That's 3 * 10 + 2 = 32.

    (Note that the fact that RtsA is abstract didn't come into this at all; that mostly only matters when you have abstract methods to worry about.)