0

What's use of overriding and how can i use it??

3rd May 2017, 5:13 PM
sahan Bandara
sahan Bandara  - avatar
2 Réponses
+ 11
Pls thoroughly read @Rrestoring explanation first! A very simple example of a often overridden method is toString of Object, see https://code.sololearn.com/c5pdVuw8Nmpe/?ref=app
3rd May 2017, 6:29 PM
Tashi N
Tashi N - avatar
+ 10
This may not be the best explanation but I hope it helps! Let's say I have a super class called Animal. I then have the sub classes, dog, cat, lion. I then go about creating some objects, and each subclass counts how many objects I create in it. I want to say the objects are equal if they have the same amount of created objects. However, the equals() method isn't defined for these kinds of objects. So dog.equals(cat) doesn't make sense. In this case I can override the equals() method. By overriding it for all Animals, I'm letting the compiler know that I'm using Animals.equals, instead of String.equals for animal objects. So I can do: Animal a = new cat(); Animal b = new lion(); if(a.equals(b)) // same number of objects, therefore equal! the equals method would look like this: @Override public boolean equals(Animal a){ return this.numObjects == a.numObjects; }
3rd May 2017, 5:27 PM
Rrestoring faith
Rrestoring faith - avatar