Originally posted by sarathy: I was wondering if this design was correct.
Well, it's not pretty, but it works. Seems like it was the best that came to the mind of the Sun developers. There might have been more elegant solutions, but I guess they also would have been more complex.
It's a compromise between elegance and simplicity, I think.
How can a JButton class ever be a subclass of Container? class. A container is one which contains other components, right?
You are right, that doesn't make much sense, semantically.
The problem is that the Sun developers wanted to reuse the AWT code for Swing by inheritance (which makes kind of sense). It would have made more sense for JComponent to inherit from Component, and to have a JContainer class that inherits from the AWT Container. But then JContainer also had to inherit from JComponent at the same time (see below), which cannot be done in Java (because Java doesn't allow mutliple implementation inheritance).
How can a Container class be a subclass of Component class ?
It's the Composite design pattern. A Container is a component that is composed of other components. And those other components can be containers again (because containers are components). Very elegant.
Does that help?
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
"sarathy", welcome to the ranch. Please take a few moments to read the Javaranch naming policy. After reading the policy, you can change your name here. We try to be friendly around here but we do have our rules, and not following the naming policy can result in having your account deleted.
Component and Container should have been interfaces. The problem is that when AWT was originally designed, nobody had much experience programming in Java. The core APIs are full of this sort of thing -- design decisions that were obvious mistakes, but now it's too late to do anything about it.
It's kind of funny if you think about it -- the Java code used by the largest number of Java developers are the APIs themselves, and yet this is some of the least idiomatic Java code in existience, since it was written by people who were brand-new to working in Java!