• Post Reply Bookmark Topic Watch Topic
  • New Topic

Question on exam....  RSS feed

 
Nicky Eng
Ranch Hand
Posts: 378
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

package test1;

1. public class Test1 {

2. static int x = 23 ;

3. }
-----------------------------------------
1. package test2;

2. public class Test2 extends test1.Test1 {

3. public staic void main(String [] args) {

4. System.out.println("x = " + x);

5. }

6. }

what is the result?

A. x = 0
B. x = 23
C. compilations fail because of an error in line 2 of Test2.
D. compilations fail because of an error in line 3 of Test1.
E. compilations fail because of an error in line 4 of Test2.


my answer is C.

but my fren said that there is no wrong with line 2 of Test2 because Test2 can extends test1.Test1.
instead he said that D is the answer because the line 3 of Test1 is the default acess, so from package test2 cant' access package test1's class's variable of x =23.

so any advice from senior here??? please help me....thanks.
 
Andrew Nomos
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Answer B is correct!

Variable x is declared as public by default and therefore visible in class Test2.
The main() method is a static method and therefore it is no problem to access the static variable x.
 
Nigel Browne
Ranch Hand
Posts: 704
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer is E as variable x is not visible in the Test2 class. Why not try to compile the code and test this for yourself ?
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
E it is. B is provided as a trap for the unwary, the other answers are stuffing to catch those who just pick an answer at random.
 
Andrew Nomos
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, I see I was mistaken.
But why does it compile properly when you put the two classes into the same package???
 
Nigel Browne
Ranch Hand
Posts: 704
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Andrew, the static variable x has the default access specifier i.e. non. This means that access is allowed inside the class and its package but not its subclasses. To be visible to subclasses in another package it would need to be protected or public.
 
Nicky Eng
Ranch Hand
Posts: 378
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i see. yeah yeah...

i get the picture already.. thanks guys. i will close it right now. thanks agian.

editted: ops, only mod could close it...so mod thank you for closing it for me.
[ June 28, 2005: Message edited by: Nicky Eng ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!