Originally posted by V Srinivasan:
Hi,
My answer is a, b and e. Class B is doing nothing in this question. Protected variable, methods can be accessed by a sub-class, so protected variable d is accessible in Class C which is extending Class A and it can be used in any type of methods in Class C except static becos static method can access outside static variable and var declared within the method. Ofcourse Class A has verymuch access to var d.
Thanks
I am interpreting
direct access as
accessing members directly without creating an instance of their class.
Based on this ,the answers are b and e.
The choice
b is correct since A.g() being a non-static method can access d which is also non-static.
The answer
e is right, since C is a sub class of A and a protected member of a class is accessible across all its subclasses irrespective of whether they are in same package or not. Note that within the non-static method of class C, the inherited variable d of superclass A can be directly accessed.
The choice
a is not an answer because A.f() is a static method and d is a non-static variable. Static methods cannot reference non-static members of its class.
The choice
c is not correct, since class B is not related to class A. However the method m of class B can access variable d of class A via an instance of class A, if class B and class A are in the same package.
( something like this can be done in class B:
public void m(){
A a = new A();
a.d=14.5;
}
However, if class B doesn't belong to the same package as class A then this possibility is completely ruled out!
NOTE: Also, since variable d is a non-static member it cannot be referenced as A.d . So
Mansoor Iqbal's System.out.println(A.d); won't compile )
The choice
d is not correct since the method s of class C being a static method cannot reference non-static inherited member d. Please note that the variable d of class A can be accessed through an instance of class A here. i.e something like that mentioned in the above example can be done irrespective of whether C and A are in the same package or not since C is a subclass of A!
Hope this helps,
A suggestion: in order to find out solutions, try compiling the code yourself. Believe me, you will find answers easily and your comprehensive ability of basic concepts will be strengthened if you do it yourself!!
Sowmya Vinay.