1

This is a code sample of inheritance while the code functions fine.I am unable to understand the output of this code kindly explain it to me.

class R {
    private void S1() {
        System.out.println("R:S1");
    }

    protected void S2() {
        System.out.println("R:S2");
    }

    protected void S1S2() {
        S1();
        S2();
    }
}

class S extends R {
    private void S1() {
        System.out.println("S:S1");
    }

    protected void S2() {
        System.out.println("S:S2");
    }
}

public class Inheritance {
    public static void main(String srgs[]) {
        new S().S1S2();
    }
}

The output is:

R:S1
S:S2

Why is the first call made to,R class' S1 while second to S class' S2.

1
  • Main is right there. Not a Homework. Commented Sep 4, 2012 at 13:52

2 Answers 2

3

R.S1 is private, so it's not called polymorphically, and S.S1 doesn't override it.

R.S2 is protected, so S.S2 overrides it, and when you call S2 on an instance of S2 (even if it's only statically known to be an instance of R), S.S2 will be called.

From section 8.4.8.1 of the JLS:

An instance method m1, declared in class C, overrides another instance method m2, declared in class A iff all of the following are true:

  • C is a subclass of A.

  • The signature of m1 is a subsignature (§8.4.2) of the signature of m2.

  • Either:

    • m2 is public, protected, or declared with default access in the same package as C, or

    • m1 overrides a method m3 (m3 distinct from m1, m3 distinct from m2), such that m3 overrides m2.

Note how m2 can't be private.

Sign up to request clarification or add additional context in comments.

1 Comment

So S.S2 overrides R.S2 .That explains why changing the access modifier of R.S2 to private would produce the desired result.Thank you Jon
0

In R, S1 is private and so cannot be overridden. The call to S1 in R#S1S2 therefore always calls R#S1. The S1 in S is totally unrelated. [Side note: you need better names.]

But S2 is not private so it can be overridden - and it is.

Java VMs can get good performance gains out of knowing that private functions cannot be overridden. And nothing, not even a descendant class, should be affected by the private details of a class.

1 Comment

Yes I got that now. And yeah I do need better names. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.