motodev
motodev

Reputation: 61

Using protected method of the parent class in another package

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?

Upvotes: 0

Views: 100

Answers (1)

Matteo NNZ
Matteo NNZ

Reputation: 12655

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.

Upvotes: 0

Related Questions