File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes static and this 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 "static and this" Watch "static and this" New topic
Author

static and this

Sasikanth Malladi
Ranch Hand

Joined: Nov 04, 2000
Posts: 175
Please read the following code:


<blockquote>What is the output of the following code?
1: class MyClass
2: {
3: static int maxElements;
4:
5: MyClass(int maxElements)
6: {
7: this.maxElements = maxElements;
8: }
9:
10: }
11:
12: public class Q19
13: {
14: public static void main(String[] args)
15: {
16:
17: MyClass a = new MyClass(100);
18: MyClass b = new MyClass(100);
19:
20: if(a.equals(b))
21: System.out.println("Objects have the same values");
22: else
23: System.out.println("Objects have different values");
24: }
25: }
A) Compilation error at line 20. equals() method was not defined.
B) Compiles fine, runtime exception at line 20.
C) Prints "Objects have the same values".
D) Prints "Objects have different values";
</blockquote>


The answer is D.
My question is: Why doesn't line 7 give a compile time error? this refers to the current object but it is referring to a static field which should be qualified with the class name and not the object reference. What's the explanation for this?
And why isn't the answer C?
Thanks,
Shashi
Harpal Singh
Ranch Hand

Joined: Oct 10, 2000
Posts: 229
Dear Sasikanth,
answer D is correct because in Object class .equals method only does shallow comparisn i.e. it does not do deep comparisn,all it does is checks the address of the object.....like = = method........Now first thing that comes to mind is then how come it works in Integer , String etc class...It has been overridden in those class to do deep comparisn.......
Now your other problem........when you say this.maxElements=maxElements..... it means class variable maxElements is equal to the local variable maxElements defined in the Constructer parameter...i.e. what ever value will be passed to Constructer MyClass will be equal to class variable which is static and whose only one copy is availaible at any given point of time............
Hope I made your confusion clear.......
Harpal
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: static and this