Tag Archives: OOP

Overriding and overloading in Java and .NET – differences, changes and gotchas

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!!!");
    }
}

Read more »

Type check and inheritance – and a nice ReSharper tip

Let’s suppose you have three classes in a simple hierarchy :

public class A
{
}

public class B : A
{
}

public class C : A
{
}

Now suppose you receive an instance of one of these classes (you don’t know the exact type to which this instance belongs). How can you determine programatically if the instance is of a type inheriting from A or it is of type A exactly?

Normally I would do the following :

var instance = ObtainInstanceFromSomeWhere(); // this method will not return null
var instanceIsExactlyOfTypeA = typeof(A) == instance.GetType();
var instanceIsOfTypeAOrAnInheritingType = typeof(A).IsAssignableFrom(instance.GetType());

All these work and are nice and dandy. However ReSharper showed me a nicer alternative to the last statement :

var instanceIsOfTypeAOrAnInheritingType = typeof(A).IsInstanceOfType(instance);

Now, pro’lly, many of you knew about this method but I didn’t! :)
Hopefully it will help someone..

Beware of switch

I am by no means against any of the instructions which exist in C#, including goto (wow, I said that). Each of them can have its place and its normal use in an application. However things can be abused and code gets nasty.

For example let’s consider we are displaying a hierarchy of people in an organization in a tree-like visual component. We will create a class that models a person :

public class Person
{
    public string Name { get; set; }
    public IEnumerable Subordinates { get; set; }
}

All is nice but some requests come in, such as : each type of person should have a distinctive icon at its left, the managers should have salutation type displayed etc.

Then you think “I know, I’ll create a PersonType enum”. That’s when things will begin to get nasty.

public enum PersonType
{
    Undefined,
    Simple,
    Manager
}

public class Person
{
    public IEnumerable Subordinates { get; set; }

    // new members :
    public PersonType Type { get; set; }
    public string Salutation { get; set; }
    private string _name;

    // modified members :
    public string Name
    {
        get
        {
             switch(Type)
             {
                 case PersonType.Simple: return _name;
                 case PersonType.Manager : return Salutation + " " + _name;
                 default : throw new InvalidOperationException();
             }
        }
        set { _name = value; }
    }

    public Image Icon
    {
        get
        {
            switch(Type)
            {
                 case PersonType.Simple: return Icons.SimplePersonIcon;
                 case PersonType.Manager : return Icons.ManagerIcon;
                 default : throw new InvalidOperationException();
            }
        }
    }
}

If you find yourself writing switches in one or more properties or methods of the class, switching on the same thing (PersonType here) then stop it. You are writing hard-to-maintain and error-prone code. Plus its inelegant. This practically is a cry for polymorphism.

The right thing to do™ is to have three classes : an abstract Person class, a SimplePerson class (inheriting the Person class) and a ManagerPerson class (also inheriting the Person class) :


public abstract class Person
{
    public virtual string Name { get; set; }
    public IEnumerable Subordinates { get; set; }
    public abstract Image Icon { get; }
    public string Salutation { get; set; }
}

public class SimplePerson : Person
{
    public override Image Icon { get { Icons.SimplePersonIcon; } }
}

public class ManagerPerson : Person
{
    private string _name;

    public override Image Icon { get { Icons.ManagerIcon; } }
    public override string Name
    {
        get
        {
            return Salutation + " " + _name;
        }
        set
        {
            _name = value;
        }
    }
}

Notice that the code is shorter, simpler to follow and understand. Furthermore although we did introduce two more classes, we also removed the PersonType enum so at a total we introduced only one more class.

WP Like Button Plugin by Free WordPress Templates