• Post Reply Bookmark Topic Watch Topic
  • New Topic

static and this  RSS feed

Sasikanth Malladi
Ranch Hand
Posts: 175
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please read the following code:

<blockquote>What is the output of the following code?
1: class MyClass
2: {
3: static int maxElements;
5: MyClass(int maxElements)
6: {
7: this.maxElements = maxElements;
8: }
10: }
12: public class Q19
13: {
14: public static void main(String[] args)
15: {
17: MyClass a = new MyClass(100);
18: MyClass b = new MyClass(100);
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";

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?
Harpal Singh
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.......
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!