1

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

3 Answers 3

1

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.!

Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

BAD inheritance : vehicle extending JComponent!
Why would it be bad, if the purpose is to be an widget that is representing a vehicle? As I wrote, if the purpose is to represent an actual vehicle (like, it has an identity), yes, then its' bad.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.