File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Defining an inside class externally? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Defining an inside class externally?" Watch "Defining an inside class externally?" New topic

Defining an inside class externally?

Joseph Macer
Ranch Hand

Joined: Apr 20, 2008
Posts: 63
Hello again!

I'm writing a multithreaded server/client chat program to build my abilities with networking and GUI. Currently, my server architecture looks like this:

You don't NEED to read all that - the point is a I have a class, inside a class, inside a class. This is because I want the member variables of the Server (top-level) class to be shared with the inner classes when they spawn new threads to deal with stuff.

My main point is - this looks messy. The inner-most class will be very complex compared to the outer two classes, and I'd rather have a separate file to define it.

Is there a way to make a dedicated inner class, defined in another source file?
[ April 25, 2008: Message edited by: Joseph Macer ]
Francesco Bianchi
Ranch Hand

Joined: Jun 22, 2007
Posts: 62
Hello Joseph,
I think you could find an answer by looking at the Observer (also known as Listener in Java world) pattern.
In your case the outer class could register to an inner one as an Observer. When some special events occurs, the inner (observed) class would just notify all its listeners (i.e. the outer class) about it. It would then be a problem of the Listener deciding what to do.

Some benefits you could obtain are:
  • a more readible (and maintanable) code
  • a more correct assignement of responsabilities to classes
  • now you would be 3 to have the three class definitions in 3 different files (that would help readibility and reuse)
  • you don't have anymore a bunch of uncontrolled threads tryng to concurrently access and modify the same couple of variables

  • If you need some examples from the Masters look into Swing code. It is heavely based on Listener pattern.
    [ April 26, 2008: Message edited by: Francesco Bianchi ]

    SCJP 5 & 6, SCWCD 5, SCBCD 5
    I agree. Here's the link:
    subject: Defining an inside class externally?
    It's not a secret anymore!