Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

accessing the super class variable

 
velan vel
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1277
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ans must be B
 
Karu Raj
Ranch Hand
Posts: 481
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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_
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic