Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Typical Overriding and Overloading Examples  RSS feed

 
JiaPei Jen
Ranch Hand
Posts: 1309
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am often asked to give overriding and overloading examples. I would say that the '+' operator is an overloading example for String object. What about overriding examples?
 
karl koch
Ranch Hand
Posts: 388
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what about google
karl
 
Kathy Sierra
Cowgirl and Author
Rancher
Posts: 1589
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hmmm... first of all, the word "overloaded" is, well, "overloaded". We have a single overloaded *operator* in Java, and that is, as you mentioned -- the "+" operator which can be used for String concatenation as well as normal arithmetic.
But if you're talking about overloading vs. overriding methods...
* Overloading: reusing a method name. The same method name but different order, type, and/or number of arguments (and optionally, a different return type). One benefit to YOU creating overloaded methods is that you make it easier for the callers of that method. In other words, YOU provide the different versions of the method to take different arguments, rather than having the caller convert his arguments into the one format your method takes. It's a way of being *nice* to the callers. Or maybe, in the case of a constructor, the caller does not HAVE all of the possible information he might have, but you still want him to be allowed to make an object, and YOU will provide default values for the pieces of information the caller does not have, or does not care about. It would be frustrating if the only way I could make an object was to know the five things I need to pass to the constructor arguments. But maybe I DO know one piece of information, and I want to specify that. The Java API is loaded with overloaded constructors, and they give the object instantiator a lot of flexibility when creating a new object.
Overriding is a whole different world. Overriding is when a subclass wants to *extend* or *replace* the behavior of the superclass. And because of the wonderous beauty of polymorphism, the overriding method will always be called at runtime even if the variable type is declared as the superclass type.
If Dog overrides the generic eat() method in Animal, then even if someone says:
Animal a = new Dog();
a.eat();
It is the DOG version of the eat() method that will be called, because it is a Dog object on the heap. (A Dog object being referred to by an Animal instance variable.)
========================================
cheers,
Kathy
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!