What is the output of this Java code?
package pack1; public class Parent { protected String message = "Hello from Parent"; } package pack1; public class Child extends Parent { public void printMessage() { System.out.println(message); } } package pack1; public class Test { public static void main(String[] args) { Child c = new Child(); c.printMessage(); } }
Remember that protected members are accessible in subclasses within the same package.
The protected member message is accessible in the subclass Child because it is in the same package. So, the program prints the message.
What will be the output of this code when run?
package pack1; public class Parent { protected String message = "Hello from Parent"; } package pack2; import pack1.Parent; public class Child extends Parent { public void printMessage() { System.out.println(message); } } package pack2; public class Test { public static void main(String[] args) { Child c = new Child(); c.printMessage(); } }
Protected members are accessible in subclasses even if they are in different packages.
The subclass Child in a different package can access the protected member message inherited from Parent. So, it prints the message.
What will happen when this code runs?
package pack1; public class Parent { protected String message = "Hello from Parent"; } package pack2; import pack1.Parent; public class NonChild { public void printMessage() { Parent p = new Parent(); System.out.println(p.message); } } package pack2; public class Test { public static void main(String[] args) { NonChild nc = new NonChild(); nc.printMessage(); } }
Protected members are not accessible from non-subclasses in different packages.
The class NonChild is not a subclass of Parent and is in a different package, so it cannot access the protected member message. This causes a compilation error.
What is the output of this code?
package pack1; public class Parent { protected String message = "Hello from Parent"; } package pack1; public class Child extends Parent { public void printMessage() { Parent p = new Parent(); System.out.println(p.message); } } package pack1; public class Test { public static void main(String[] args) { Child c = new Child(); c.printMessage(); } }
Protected members are accessible within the same package regardless of reference type.
Since Child and Parent are in the same package, Child can access the protected member message even through a Parent reference.
Which statement about the protected access modifier in Java is TRUE?
Think about how protected members behave with subclasses and packages.
Protected members are accessible within the same package and also accessible to subclasses even if those subclasses are in different packages.
