Foraying even more in the fundamentals of Java (coming from a .NET background) I’ve come across some interesting things, along with changes in Java SE 5. But first let’s clear up a bit these two notions (overloading and overriding).
Overriding
Is a language feature that allows a subclass/inheriting class to have a method identical (we’ll later see a slight exception to this) to the one in the base class/superclass in every way except the implementation. That is, to have the same return type, the same name, same paramater types, same parameter order, just the code (and the parameter names) can differ.
This is by no means a definitive definition, Wikipedia, .NET CLS’s and JLS may very well differ slightly.
A typical C# overriding example (yes, I also dislike animal examples but they are so eaaaasyyyy to come up with) :
public class Dog { public virtual void MakeSound() { Console.WriteLine("Bark."); } } public class Hound : Dog { public override void MakeSound() { Console.WriteLine("Wooofff!!!"); } }
Java developers unaware of the intricacies of C# will wonder what is that “virtual” thing. In C# all methods are “final” (sealed) by default unlike Java where methods are “virtual” (non-final / non-sealed) by default. This is a profound difference which we’ll discuss later. The “:” stands for “extends”. We’ll discuss the “override” keyword soon, also.
The equivalent piece of code in Java would look like :
public class Dog { public void makeSound() { System.out.println("Bark."); } } public class Hound extends Dog { public void makeSound() { System.out.println("Woofff!!!"); } }
Recent Comments