Hi,I am preparing for sjcp exam.my quetion is about the protected class. it have one super and sub class example ,below example i read from one pdf.package certification;public class Parent { protected int x = 9; // protected access}----------------------------package other;import certification.Parent;class Child extends Parent {public void testIt() { System.out.println("x is " + x); // No problem; Child inherits x Parent p = new Parent(); // Can we access x using the p reference? System.out.println("X in parent is " + p.x); // Compiler error!}}when i compile this code it dosen't give any error.even though both classes are in diffrent package. but in pdf it mentioned that it gives an error because you are trying to access the protected variableusing the instance of the super class if the above code is write then what is logic behind the protected member of super class and if sub classin different package try to access the member of the super class.
Questions by Thakkar Nirav answers by Thakkar Nirav
Showing Answers 1 - 8 of 8 Answers
Hi,I am preparing for sjcp exam.my quetion is about the protected class. it have one super and sub class example ,below example i read from one pdf.package certification;public class Parent { protected int x = 9; // protected access}----------------------------package other;import certification.Parent;class Child extends Parent {public void testIt() { System.out.println("x is " + x); // No problem; Child inherits x Parent p = new Parent(); // Can we access x using the p reference? System.out.println("X in parent is " + p.x); // Compiler error!}}when i compile this code it dosen't give any error.even though both classes are in diffrent package. but in pdf it mentioned that it gives an error because you are trying to access the protected variableusing the instance of the super class if the above code is write then what is logic behind the protected member of super class and if sub classin different package try to access the member of the super class.
Profile Answers by Thakkar Nirav Questions by Thakkar Nirav
Questions by Thakkar Nirav answers by Thakkar Nirav