Forums Register Login

Question on exam....

+Pie Number of slices to send: Send
 


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.
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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 ?
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
Ok, I see I was mistaken.
But why does it compile properly when you put the two classes into the same package???
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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 ]
Villains always have antidotes. They're funny that way. Here's an antidote disguised as a tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 517 times.
Similar Threads
Mock Exam Qn.(What is the result)
Package level question.
package
error in result
Compilation fails
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 16:44:05.