Always Get Better

Posts Tagged ‘polymorphism’

C#: Instantiating a class of Unknown Type

Saturday, April 5th, 2008

The project I am currently working on has several dozen different types of Form classes, each of which is accessible from a common menu strip. Rather than repeatedly instantiating each of the forms from the menu item handlers, I wanted to funnel the request to a single function.

The problem is: How do you instantiate a form when the type is unknown?

The code snippet is:

[source:c#]
CreateForm( typeof(CustomFormType) );

Form CreateForm( Type formType )
{
return (Form)Activator.CreateInstance(formType);
}
[/source]

Breaking Java’s Rules: Instantiating an Interface

Friday, February 8th, 2008

Here’s a geeky party trick:

Abstract classes in Java cannot be instantiated. Here we’re going to consider ways in which a button can be programmed within a JPanel. ActionListener is used to react to the button event, but ActionLister is an interface (pure abstract class) so in order to use it you have to derive a class from it and implement actionPerformed.

For example, you can’t do this:

[source:java]
ActionListener buttonListener = new ActionListener();
[/source]

You have to do this:

[source:java]
public class ButtonListener
{
public void actionPerformed( ActionEvent event )
{
}
}

ButtonListener buttonListener = new ButtonListener();
ourJButton.addActionListener( buttonListener );
[/source]

However, this code is valid:

[source:java]
ourJButon.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent event )
{
}
} );
[/source]

What’s going on? It would appear that we are instantiating a new ActionListener and giving it an actionPerformed() method. We’ve succeeded in giving our button a listener without first creating a class to handle the event.

Anonymous Inner Classes

Of course we aren’t really instantiating ActionListener – it was a trick. What this does is create an anonymous inner class only in this part of our code. Check it out – when you compile your code, javac will create extra class files for our ActionListener.

For one-off buttons, using anonymous inner classes is an excellent way of reducing code bloat and improving the readability of your programs. There are drawbacks of course, which I’ll go into detail in another article, another day.