When attempting to create an object of the parent class, which has a protected constructor, I tried using a child class reference and was able to create the object successfully. However, when using a parent class reference, it resulted in a compilation error.
When attempting to create an object of the parent class, which has a protected constructor, I tried using a child class reference and was able to create the object successfully. However, when using a parent class reference, it resulted in a compilation error.
This is the code used:
package secondPackage;
public class AccessPra {
protected AccessPra() {
System.out.println("protected constructor");
}
}
package firstPackage;
import secondPackage.*;
public class MainClass extends AccessPra {
public static void main(String[] args) {
AccessPra obj1 = new AccessPra(); // Throwing Error
MainClass obj2 = new MainClass(); // This line is working
}
}
Because they are in different packages, that has to do with access modifiers, if you move your class into the same package it will work! Check this table to understand access modifiers: https://www.javatpoint.com/access-modifiers
like this:
If you want different packages and use protected methods using inheritance you can also do this:
As you can see, as the mainclass extends AccesPra, it inherits the methods from the parent Class and because of that you can use them when they are protected.
Hope that helps!