Which statement regarding the following code is correct?
class MyBaseClass { public int i = 10; private int j = 20; } class MyClass extends MyBaseClass { private int i = 30; //1 public int k = 40; } class MySubClass extends MyClass{ } public class Main{ public static void main (String args []){ MySubClass c = new MySubClass (); System.out.println (c.i); //2 System.out.println (c.j); //3 System.out.println (c.k); } //from www .j a v a2 s .c o m }
Select 1 option
Correct Option is : B
You cannot access c.i because i is private in MyClass.
But you can access ((MyBaseClass)c).i because i is public in MyBaseClass.
Remember that member variables are shadowed and not overridden.
So, MyClass's i shadows MyBaseClass's i and since MyClass's i is private, you can't access MyBaseClass's i unless you cast the reference to MyBaseClass.
You cannot access c.j because j is private in MyBaseClass.