I have seen various articles on differences between the protected and package private modifiers. One thing I found contradictory between these two posts
Isn't "package private" member access synonymous with the default (no-modifier) access?
In this the accepted answer says that
The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.
Why the protected modifier behave differently here in Java subclass?
In this the accepted answer says that
To satisfy protected level access two conditions must be met:
- The classes must be in the same package.
- There must be an inheritance relationship.
Aren't they contradictory? from my understanding of other articles, the first post gives the correct answer that protected == package-private + subclass in other package.
If this statement is correct, then why this code fails with the following error message on my subclass Cat on line 17
The method testInstanceMethod() from the type Animal is not visible
my code for super and subclass are below.
package inheritance;
public class Animal {
public static void testClassMethod() {
System.out.println("The class" + " method in Animal.");
}
protected void testInstanceMethod() {
System.out.println("The instance " + " method in Animal.");
}
}
package testpackage;
import inheritance.Animal;
public class Cat extends Animal{
public static void testClassMethod() {
System.out.println("The class method" + " in Cat.");
}
public void testInstanceMethod() {
System.out.println("The instance method" + " in Cat.");
}
public static void main(String[] args) {
Cat myCat = new Cat();
Animal myAnimal = myCat;
myAnimal.testClassMethod();
myAnimal.testInstanceMethod();
}
}
Please clarify why the above code fails. That would be very useful. Thanks