0

I have Tadpole class that extends Frog, as follows:

1: package animal;
2: public class Frog {
3:   protected void ribbit() { }
4:   void jump() { }
5: }

1: package other;
2: import animal.*;
3: public class Tadpole extends Frog {
4:   public static void main(String[] args) {
5:     Tadpole t = new Tadpole();
6:     t.ribbit();
7:     t.jump(); // doesn't compile due to default access
8:     Frog f = new Tadpole();
9:     f.ribbit(); // doesn't compile 
10:    f.jump(); // doesn't compile due to default access
11: } }

Lines 7 and 10 do not compile due to the package-private access of the jump() method.

I understand that upcasting of Tadpole class into Frog class on line 8 will allow the parent instance member (the ribbit method) to be accessed from the subclass since the method is not overwritten.

Protected methods should be able to be accessed from a subclass whether it's in the same package or different package right? If so, why doesn't line 9 compile?

motodev
  • 13
  • 5
  • protected methods can be accessed from within the package and outside the package but within the child class (used inside the child class). What you are trying to do is a public access to a protected method from outside the package – Islam Elbanna Mar 09 '23 at 10:07
  • If instead of protected the method ribbit() was private, would you have expected it to be accessible using the same code? – Matteo NNZ Mar 09 '23 at 10:07
  • No line 9 you are trying to access method `ribbit` of a new object `Tadpole` so you are no longer inside the `Tadpole` class you just access the public API of that object – Islam Elbanna Mar 09 '23 at 11:45

1 Answers1

0

A protected method is a method that can be invoked:

  • Either inside the class Frog that declares it
  • Or inside the instance source code of any subclass of Frog
  • Or ultimately from within the same package

In your specific case, you are in neither of these cases. The tricky part may be that you are writing your call inside the source code of Tadpole, that is a subclass of Frog (so you may say hey, I'm in the case two).

But actually it's not like that. You are not invoking the method from an instance method of the class Tadpole, rather you are in a static context (a main method), where you are creating an instance of Frog f, and you're trying to access the method from that instance f. You may be anywhere else, and it would be the same thing.

If the method ribbit() was private, you wouldn't have been suprised that you couldn't do f.ribbit(). But the same goes for protected, if you think the same way.

Matteo NNZ
  • 11,930
  • 12
  • 52
  • 89
  • @user16320675 right for the package, I've added it (it's not a way I actually use it so I forgot it). As for the instance source code, I mean in the instance code (not static) of the class which necessarily is in the class source code. – Matteo NNZ Mar 09 '23 at 14:50