h1

Inner classes.

April 17, 2010

Why are they usefull?

I would say that I would use them just to let the next programmer know that I only intend this classes to be used in this particular class and in no other place. Just like that.

I was working on some project and we had to deal with using the RaphaelGWT port of RaphaelJS.

We stumbled upon they were a lot of inner classes. Have a look at this snippet of the code:

package com.hydro4ge.raphaelgwt.client;

import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.Widget;
import java.util.ArrayList;

public class Raphael extends Widget {

    private RaphaelJS overlay;
    private final ArrayList shapes = new ArrayList();

    public Raphael(int width, int height) {
        super();
        Element raphaelDiv = DOM.createDiv();
        setElement(raphaelDiv);
        overlay = RaphaelJS.create(raphaelDiv, width, height);
    }

    public class Shape extends Widget {
    }

    public class Circle extends Shape {
    }

    public class Text extends Shape {
    }

    public class Rect extends Shape {
    }

    public class Ellipse extends Shape {
    }

    public class Image extends Shape {
    }

    public class Path extends Shape {
    }
}

That code was taken from RaphaelGWT repository.

The thing is that those classes are used within that same class, over and over again, and nowhere else. So basically, from this particular class, I can say that if we have to use some classes that are really part of the containing class and will never ever be used outside of it, we should just create it as an inner class.

I still have to check (actually i should just google for it and that’s it) what the scope of things are for those inner classes and the containing class… I mean, can the inner class methods view the private attributes of the container class?
Why? Why not?

How about inheritance and all that stuff?

Well, surely it’s a long subject.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.