wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes accessing the super class variable  Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "accessing the super class variable  " Watch "accessing the super class variable  " New topic
Author

accessing the super class variable

velan vel
Ranch Hand

Joined: Nov 15, 2005
Posts: 137
hai ranchers why this code is giving
compiler error
can any one explain


1. package test1;
2. public class Test1 {
3. static int x = 42;
4. }
1. package test2;
2. public class Test2 extends test1.Test1 {
3. public static void main(String[] args) {
4. System.out.println("x = "+ x);
5. }
6. }

What is the result?
A. x = 0
B. x = 42
C. Compilation fails because of an error in line 2 of class Test2.
D. Compilation fails because of an error in line 3 of class Test1.
E. Compilation fails because of an error in line 4 of class Test2.
Answer: C


by velan vel
Niranjan Deshpande
Ranch Hand

Joined: Oct 16, 2005
Posts: 1277
ans must be B


SCJP 1.4 - 95% [ My Story ] - SCWCD 1.4 - 91% [ My Story ]
Performance is a compulsion, not a option, if my existence is to be justified.
Karu Raj
Ranch Hand

Joined: Aug 31, 2005
Posts: 479
No Niranjan .......

The answer is C .Let me explain why
The code test for Access modifiers...

Here.... Look at line 3
1. package test1;
2. public class Test1 {
3. static int x = 42;///it is default not a public or protected or private.
4. }
1. package test2;
2. public class Test2 extends test1.Test1 {
3. public static void main(String[] args) {
4. System.out.println("x = "+ x);
5. }
6. }

So default mean it can be only see inside the same package only . So at line 4 it is try to access the line 3 which it cannot see ...so compile error.

if you want to compile fine then change at line 3 as
public static int x = 42 or protected static int x = 42.

Also remember you can access protected member only through inheritance means subclass.

Hope you got now .
Mike Noel
Ranch Hand

Joined: Dec 15, 2005
Posts: 108
Karthik, your analysis makes sense but the answer then would be E -- compliation error on line 4. I'm not seeing why the compilation error is happening on line 2.

_M_


Mike Noel
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: accessing the super class variable
 
Similar Threads
Compilation fails
Package level question.
package
error in result
Mock Exam Qn.(What is the result)