开发者

using Inheritence with GUI (graphical user interfaces) in Java


I work on inheritence with GUI (graphical开发者_运维知识库 user interfaces)

let me explain for example I made super class which is vehicle and the subclass is car, so the code to make inheritence will be

public class Car extends Vehicle

then I want to build the class Car as JFrame like

public class Car extends JFrame implements ActionListener {

so the problem is that I couldn't put both codes in the same class, and I need to do that.

anyone help me. thanks in advance

I wish that the question would be clear


consider the example :

class A extends B

Before inheriting , think twice if A IS A KIND OF B, now tell me if CAR IS A TYPE OF FRAME?? NO?? Then do not inherit.

create a JFrame, and add car to it...


Better solution : Divide Car to Model-View-Controller classes.. and add Car's View to the Screen (class Sceen extends JFrame)

Now ur Car's MVC will inherit the Vehicle's MVC respectivily.! Now it makes sense : CAR IS A VEHICLE.

More Better : instead of adding car's view to Screen (AGGREGATION) , have a function in Screen which gets the Car's view object and paint it in Screen (which is a DEPENDENCY). Thus achieving low coupling.!


Java is not allowing multiple superclasses by design (and pretty good reasons.)

However, there is nothing to stop you from letting Vehichle extend JComponent(*), and Car extending Vehicle.

public class Car extends Vehicle {
...
}

*) JComponent is probably a better choise for the base-class, as JFrame is a rather special gui-element. A JComponent can be added to a JFrame instead.

Also, this design assumes that the primary purpose of a Vehicle (etc) is to be a graphical representation of a vehicle. Othervise, you might consider dividing the behaviour in a VehicleViewer and Vehicle, for instance if the Vehicle actually represents a real-life vehicle, you are loading/storing Vehicles from a database etc.


Rename the Car class to CarView or reference the other Car class using it's fully qualified name, e.g. myapp.domain.Car rather than just Car.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜