+ 1

Writing an equals method to compare two objects's contents - Java

Could someone explain the line 73, 74 in this code for me? I don't understand what is this "object2.symbol" means in the code. - Thank you in advance! https://code.sololearn.com/cHuxcV55TB89/#java

4th Jan 2020, 7:49 PM
feof
feof - avatar
8 odpowiedzi
+ 6
The class Stock has two attributes: String symbol; double sharePrice; Lets say you have two objects: Stock a and Stock b. a has its own String symbol b has its own String symbol Same for sharePrice. Now you call a.equals(b). To compare two Strings use equals(). double is primitive, here you can use ==. a is the object which calls the method, b is the parameter. Inside the method b gets object2 //btw: I prefer to use the keyword this this.symbol.equals(object2.symbol) && this.sharePrice == object2.sharePrice -> a.symbol equals b.symbol AND a.sharePrice equals b.sharePrice? ->if yes return true, else return false Hope it is not too confusing ;)
4th Jan 2020, 8:18 PM
Denise Roßberg
Denise Roßberg - avatar
+ 4
LeoBeliik equals() is a method which all objects inherits from the Object class. You can also use equals() to compare two Lists, Arrays or whatever Also if you write own classes your objects has an equals() method. But you have to override it, if you want to use it.
4th Jan 2020, 8:25 PM
Denise Roßberg
Denise Roßberg - avatar
+ 2
coip symbol and share price are private. To get access to the values you have to use the getters. getSymbol() and getSharePrice() In another class: Stock s = new Stock("abc", 1.2) String symbol = s.getSymbol(); double sharePrice = s.getSharePrice();
4th Jan 2020, 8:49 PM
Denise Roßberg
Denise Roßberg - avatar
4th Jan 2020, 8:55 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
Thank you Denise Roßberg. I already know about Getters and Setter. I just want to know about wht this syntax means: instance.nameOfField (eg: object2.symbol).
4th Jan 2020, 9:01 PM
feof
feof - avatar
+ 1
coip instance = object of a class fields = attributes object2 is an instance of class Stock symbol is the name of the field.
4th Jan 2020, 9:05 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
you should have to overload hashcode() method and equals() method
6th Jan 2020, 10:59 AM
Monu Kumar
Monu Kumar - avatar
0
Thanks Denise for your reply. I haven’t learned the keyword this yet. I’ve a questions also. If I want to access a private field (e.g., symbol and sharePrice) in another class, should I write an instance of this class followed by a dot and the name of the field?
4th Jan 2020, 8:30 PM
feof
feof - avatar