• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Carey Brown
  • Mikalai Zaikin
Bartenders:
  • Lou Hamers
  • Piet Souris
  • Frits Walraven

Tell me the output?

 
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class MyClass
{
static int maxElements;

MyClass(int maxElements)
{
this.maxElements = maxElements;
}

}

public class Q19
{
public static void main(String[] args)
{

MyClass a = new MyClass(100);
MyClass b = new MyClass(100);

if(a.equals(b))
System.out.println("Objects have the same values");
else
System.out.println("Objects have different values");
}
}


equals() method was not overrided but still it compiles fine.Why?
 
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Manoj,


Every class inherits Object class so as your class "MyClass" does; You class inherits Object(daddy of all classes) class's equals() method whose definition is as following:


public boolean equals(Object o) {
return this==o;
}

So when you do like
if(a.equals(b)) {
}
a and b are objects of MyClass, so where Object is required as Argument any object of Java can fit there.


Regards,
cmbhatt
 
Manoj Mani
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
ok thanks.........
 
Ranch Hand
Posts: 257
Hibernate Firefox Browser Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello,

It compiles fine and gives the print in else part. The parent class for all classes in java is java.lang.Object class got default implementation for equals method.

 
So it takes a day for light to pass through this glass? So this was yesterday's tiny ad?
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic