Java creating equals method

  • Java
  • Thread starter schapman22
  • Start date
  • Tags
    Java Method
  • #1
I'm having to create a temperature class for one of my assignments, were just getting into oop. Basically we just create a few constructors, accessor and mutator methods. The mutator methods are where celsius-farenheit conversions are. And we need to make an equals method which I know how to do but I don't know how you check to see if a fahrenheit object and a celsius are equal. Like if one object is set to 32F and another is 0C then it should return true.
Technology news on
  • #2
Have a think about how you would store the temperature data in your class, there's a few ways you could try. When you have the data stored appropriately you need a method that takes two parameters (two temperatures, one in fahrenheit and one in celsius) and uses the conversion formula to check if the values are equivalent, and if they are, return true.

It's a good exercise and it's worth figuring out the small details for yourself.

1. What is the purpose of the "equals" method in Java?

The "equals" method in Java is used to compare two objects to determine if they are equal or not. This is an important method for determining object equality in Java because it allows for more precise control over how objects are compared.

2. How does the "equals" method work in Java?

The "equals" method works by comparing the values of two objects. It first checks if the two objects are of the same type, and if they are, it then compares their values using the "==" operator. If the values are equal, the method returns true, indicating that the objects are equal. If the values are not equal, the method returns false.

3. Can the "equals" method be overridden in Java?

Yes, the "equals" method can be overridden in Java. This allows for custom implementation of object comparison, which can be useful when working with complex or custom objects.

4. What is the difference between "==" and "equals" in Java?

The "==" operator compares the memory addresses of two objects, while the "equals" method compares the values of two objects. This means that two objects can have the same values, but different memory addresses, and therefore would not be considered equal using the "==" operator. However, they could be considered equal using the "equals" method if their values are the same.

5. How can I create a custom "equals" method for my Java objects?

To create a custom "equals" method, you will need to override the default implementation provided by the Object class. In your custom method, you can define how you want your objects to be compared and what criteria make them equal. This can include comparing specific attributes or properties of the objects. It is important to follow the guidelines for implementing the "equals" method, as outlined in the Java documentation, to ensure proper functionality.

Suggested for: Java creating equals method