Composition vs. Inheritance

Hello again world.
I finally got around to buying Bruce Eckel's book Thinking in Java. After reading the chapter "Reusing Classes", I tried to write a program using both techniques just to see if it would compile:class  Building
   protected  boolean  isBrick;
   protected  boolean  isRoofPitched;
class  Window
   public  void  setTinted(boolean  isTinted) {}
class  Door
   public  void  open() {}
   public  void  close() {}
   protected  Window  window = new  Window();
public  class  House  extends  Building
   private  Window  windows[] = new  Window[12];
   private  Door  frontDoor;
   public  House()
      isBrick = false;
      isRoofPitched = true;
      frontDoor = new  Door();
      frontDoor.window.setTinted(true);
      windows[0] = new  Window();
      windows[0].setTinted(false);
      for (int  x = 0 ; x < 12 ; x++)
         windows[x] = new  Window();
   public  static  void  main(String[]  params)
      House  house = new  House();
      house.frontDoor.open();
      System.out.println("Welcome to your new home.");
      System.out.println("You may want to install some plumbing.");
}I would appreciate any comments or criticisms on how demonstrative my logic is.
Thank you one and all.
Ciao for now.

I think you have used inheritance and composition in a correct way. For example a House IS-A Building but a House HAS-A Window and it HAS-A Door etcetera.

Similar Messages

  • Hi all, Composition vs Inheritance

    Hi,All which is better Composition or Inheritance in the realtime issues??
    Thanks in Advance,

    What does real time have to do with it? Composition can almost always be used where inheritance can, with less tricky side effects
    You're welcome in retrospect :-)

  • Composition versus inheritance

    I am working on a large project with multiple levels of control.  There is a top system level, an intermediate subsystem level, and a low level component.  I am interested in implementing a configuration from a file for all 3 levels.  So, I am contemplating 2 solutions.  This can allow me to edit the config file and not require a recompile of the code.  So here are the options I am thinking about to enable configuration.
    1.  Make a parent class that is "Configurable".  Have the System, Subsystems and Components inherit from this "Configurable" object.  Have dynamic dispatch methods for Read Configuration and Write Configuration, etc.  Define a override method for these for each thing.  This only adds one class to the architecture, but it is the parent of almost everything.
    2  Make a "Configuration" class.  Give each system, subsystem and component a child class of Configuration.  Such that each thing "has a" configuration.  This would add an additional class for every system, subsystem and component.
    Thoughts?
    Casey Lamers
    Phoenix Nuclear Labs
    [email protected]

    Hi,
    extending an Application Module is design best practices in that it allows you to build your own base framework classes and reuse existing code. Nesting an application Module puts it under the same transaction context as the root application module.
    This is a different usecase and thus there no need to decide for one versus the other
    Frank

  • When to use inheritance and When to use Composition

    java support both inheratiance and composition .I also know "is a" and
    "has a realitionship" but there is always a problem with me to understanding whethere i have to use extends or having a object of a class has a member of othere class.
    and also "A pure OOP must support polimorphisim,inheretiance,encapluction,Abstraction and Composition" correct me if i am wrong
    thank you and have a nice day.

    Bruce Eckel, author of Thinking In Java, has this to say about composition vs. inheritance:
    When deciding between inheritance and composition, ask if you need to upcast to the base type. If not, prefer composition (member objects) to inheritance. This can eliminate the perceived need for multiple base types. If you inherit, users will think they are supposed to upcast.
    Choose composition first when creating new classes from existing classes. You should only used inheritance if it is required by your design. If you use inheritance where composition will work, your designs will become needlessly complicated.
    Bill Venners: Composition versus Inheritance
    Use inheritance (of implementation) only when the class satisfies the following criteria:
    1) "Is a special kind of," not "is a role played by a";
    2) Never needs to transmute to be an object in some other class;
    3) Extends rather than overrides or nullifies superclass;
    4) Does not subclass what is merely a utility class (useful functionality you'd like to reuse); and
    5) Within PD: expresses special kinds of roles, transactions, or things.
    -- from Java Design: Building Better Apps and Applets (2nd Edition), by Peter Coad and Mark Mayfield

  • Java Programming: Selective Inheritance possible ?

    Hello Java pros,
    I am looking for help on ideas to selectively inherit public methods of a super-class.
    eg.I create a new class z_stack to implement the classic features of the Stack Data Structure, by 'extending' the vector class.
    z_stack has methods push(Object, int), pop(int) and peek(int).
    But because z_stack extends vector, the public methods of vector,
    get(int), insertElementAt(Object, int) & remove(int)
    also get inherited by z_stack.
    Because Stack is, per definition, a "controlled" vector that needs to enforce a LIFO mechanism and to avoid confusion among eqvivalent methods (eg. peek = get), I would like to "suppress"/make-invisible the 'get', 'insertElementAt' and 'remove' methods inherited from vector.
    In other words, I want z_stack to inherit all other properties of vector excluding the methods 'get', 'insertElementAt' and 'remove'.
    Would this be possible ?
    Thanks in advance for your help.
    Sree Nidhi

    fyi -
    #1
    From the book �Core Java 2� Volume II by Cay Horstmann, chapter 2 Collections, Section Stacks
    �However, the Stack class extends the Vector class, which is not satisfactory from a theoretical perspective � you can apply such un-stack-like operations as insert and remove to insert and remove values anywhere, not just the top of the stack.�
    #2
    From the book �Effective Java� by Joshua Block (who designed and implemented the Java Collections Framework), Item 14 Favor Composition Over Inheritance
    "Inheritance is appropriate only in circumstances where the subclass really is a subtype of the superclass"..."It is often the case that B should contain a private instance of A and expose a smaller and simpler API"..."There are a number of violations of this principle in the Java platform libraries. For example, a stack is not a vector, so Stack should not extend Vector."
    ("Java Programming Language" and "Effective Java" have helpful discussions on composition and forwarding.)

  • Annotation's inheritance

    I think it would be wonderfull to have Annotation's inheritance,
    for example there is a javax.persistence.Entitiy and org.hibernate.annotations.Entity, the former is created for extending properties of the first; it would be nice to make second one extends the first one, don't you think so?

    I think it would be wonderfull to have Annotation's
    inheritance,
    for example there is a javax.persistence.Entitiy and
    org.hibernate.annotations.Entity, the former is
    created for extending properties of the first; it
    would be nice to make second one extends the first
    one, don't you think so?This capability was considered by the JSR 175 expert group (http://www.jcp.org/en/jsr/detail?id=175) but rejected . The question is addressed in their design FAQ:
    "Why don't you support annotation subtyping (where one annotation type extends another)?
    It complicates the annotation type system, and makes it much more difficult to write "Specific Tools" (per the taxonomy in Section VI). "
    There is also the general advice to favor composition over inheritance ("Effective Java" item 14).

  • Interesting difference between books and tutorials

    I started coding in Java about four years ago. When I started I learned from a book (that I no longer have), I think it was "Sam's Teach Yourself Java in 24 Hours". I was just a kid then and I became fairly proficient in all of the basic requirements and such. Now, four years later, I am looking into getting back to Java when I can find the time, and possibly getting a certification. Instead of the book, I now use the online tutorials and API docs. Something I noticed about the tutorials is that they use coding methods that I never saw in the book. For instance from this tutorial on using the SpringLayout, the code follows this syntax:
    import /*neccessary items*/
    public class SpringDemo1 {
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the                  <----I didn't add this. Guessing it has something
         * event-dispatching thread.                                    to do with preventing the thread from crashing...?
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("SpringDemo1");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //SpringLayout code here....
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }whereas, when I learned from the book, I always did this and I still do:
    import /*neccessary items*/
    public class myClass extends JFrame {
        public myClass() {
            //set up GUI here
        public static void main(String args[]) {
            myClass mc = new myClass();
    }If I am going to get my certification, I don't want to be using practices that could cause a program to crash and get someone angry at me. If I am doing something wrong, please chew me out. It's better than losing a job...

    The book is old-fashioned, that's all. Neither version of the code is so bad that it will crash and you will lose your job and become a drug addict accosting people on the street for money.
    The "extends JFrame" version was the usual way to write things back in the early days of Java. And then people started thinking more about object orientation, and noticed that there was nothing in most Swing programs which created a modified JFrame. They simply used the features of a JFrame to get their work done.
    So under the flag of "Prefer composition to inheritance", the OO people rewrote the standard Swing application to do that. And so they should... Java is an object-oriented language, after all, so why not do things right? Let's not extend JFrame (inheritance) if we can just create one and use it (composition).
    Of course they couldn't go back and change all the paper books and all the thousands of programs that people had already written in the old way, but they could change the tutorials. And they did.
    So my suggestion would be to follow the style shown in that tutorial. You won't lose your job over it. In fact being able to explain why you did it might even improve your status at your job.

  • How can I disable a method from a direved class

    I am extended TreeSet for an assigment with some new functionality.
    This new class is rbTree.
    I need to disable all of the old functions so that if a user creates a new rbTree he will only be able to use the methods defined in rbTree.
    rbTree uses some of treeSets methods using super.
    I now how to just overwrite them but I think I should let the user know those methods are unsupported, by throwing an exception. I can't throw any exceptions because most of treeSets methods don't.
    I know there is an easy way to do this, and I don't think I should just leave them blank.
    Any ideas?
    thanks in advance
    -Marc

    If you have a new class that extends TreeSet that shouldn't expose any of the TreeSet methods, don't extend TreeSet. Prefer composition over inheritance. You can use a TreeSet as a private member within your class; e.g. your new class has-a TreeSet, rather than is-a TreeSet. This way you control which functionality of the TreeSet to use, but only expose your new methods.
    Also, you should read and implement Code Conventions for the Java&#153; Programming Language - it will help you and others understand/maintain your code.
    Example:import java.util.TreeSet;
    public class RbTree
        private TreeSet set = new TreeSet();
         * only allow a specific type of object (my.pkg.MySpecialObject) to be added to the set.
        public add(MySpecialObject mso)
            set.add(mso);
        // other methods follow...
    }

  • Output not appearing when using SwingWorker?

    Hi guys,
    I'm desperate here. Any help would be great.
    I'm using SwingWorker to append info into a Text Area, but when I run the code, nothing happens in the TextArea. Here's the code
    public class RLGUIFrame extends javax.swing.JFrame implements ActionListener{
        private final GridBagConstraints constraints;
        JTextArea movementText;
        private final Border border =
            BorderFactory.createLoweredBevelBorder();
        private final JButton startButton, stopButton;
        private RobotTask robTask;
         public static final int GRID_SIZE=10;
         public static final int NUMBER_OF_TIMES=1000;
        private JTextArea makeText() {
            JTextArea t = new JTextArea();
            t.setEditable(false);
            t.setAlignmentX(RIGHT_ALIGNMENT);
            t.setBorder(border);
            getContentPane().add(t, constraints);
            return t;
        private JButton makeButton(String caption) {
            JButton b = new JButton(caption);
            b.setActionCommand(caption);
            b.addActionListener(this);
            getContentPane().add(b, constraints);
            return b;
        public RLGUIFrame() {
            super("RL");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Make text boxes
            getContentPane().setLayout(new GridBagLayout());
            constraints = new GridBagConstraints();
            constraints.insets = new Insets(3, 10, 3, 10);
            movementText = makeText();
            //Make buttons
            startButton = makeButton("Start");
            stopButton = makeButton("Stop");
            stopButton.setEnabled(false);
            //Display the window.
            pack();
            setVisible(true);
        private class LocReport{
             private Location loc;
             private double val, rand;
             private boolean KS;
             LocReport(Location L, double value, boolean KillSpot, double random){
                  this.loc = L;
                  this.val = value;
                  this.KS = KillSpot;
                  this.rand = random;
    private class RobotTask extends SwingWorker<Void, LocReport> {
        @Override
        protected Void doInBackground() {
            Grid grid = new Grid( GRID_SIZE );
             Location startPosition = grid.getLoc( 8, 8 );
             Robot jerry = new Robot( startPosition );
             Random rand = new Random();
             grid.fillGrid();
            //EastWestSentry ews = new EastWestSentry( grid.getLoc(5, 5));
             grid.getLoc( 3 , 3 ).setValue( 1.0 );
             grid.getLoc( 7 , 7 ).setValue( 0.0 );
             for( int i = 0; i < GRID_SIZE; i++){
                  grid.getLoc( i, 4 ).isKillSpot = true;
             grid.getLoc(4, 5).isWindy    = true;
             grid.getLoc(7, 5).isKillSpot = true;
             grid.getLoc( 6, 4 ).isKillSpot = false;
             for( int i=0; i < NUMBER_OF_TIMES; i++ ){
             while ( jerry.getLocation() != grid.getLoc( 3 , 3 ) ){
             Location L = jerry.getLocation();
             double value = L.value;
             double random = rand.nextDouble();
             boolean isKS = L.KillSpot();
             publish( new LocReport(L,value,isKS,random) );
              if(jerry.getLocation().isWindy == true)
                   jerry.move( grid.getLoc(7, 5) );
              if( jerry.getLocation().hasSentry )
                        jerry.getLocation().isKillSpot = true;     
              if(jerry.getLocation().isKillSpot == true){
                   if( rand.nextDouble() > 0.5 ){
                        System.out.printf("Lucky this time. This killspot didn't kill me.\n");
                   }else{
                   grid.getLoc(jerry.getXCoord(), jerry.getYCoord()).setValue(-1);
                   jerry.regenerate( startPosition );
              if(rand.nextDouble()>0.8){
                   System.out.printf("I'm going exploring!\n");
                   jerry.exploratoryMove();
              else{
                   //ews.patrol();
                   jerry.move();
                   if( jerry.getMyPreviousLocation().isKillSpot &&
                        jerry.getMyPreviousLocation().getValue() > 0.0 ){
                        jerry.getMyPreviousLocation().setValue(-1);
             return null;
        protected void process(List<LocReport> locs) {
             LocReport location = locs.get( locs.size() - 1);
             movementText.append("========================\n");
             movementText.append("Robot is at location : " + location.loc.getXCoord() +
                                   ", " + location.loc.getYCoord() + "\n");
             movementText.append("It's value is : " + location.val + "\n");
    public void actionPerformed(ActionEvent e) {
        if ("Start" == e.getActionCommand()) {
            startButton.setEnabled(false);
            stopButton.setEnabled(true);
            (robTask = new RobotTask()).execute();
        } else if ("Stop" == e.getActionCommand()) {
            startButton.setEnabled(true);
            stopButton.setEnabled(false);
            robTask.cancel(true);
            robTask = null;
        * @param args the command line arguments
        public static void main(String args[]) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    new RLGUIFrame();
    }Edited by: zimmerPlease on Mar 23, 2010 3:58 PM

    You're adding both components with the same GridBagConstraints without setting any of its attributes. Follow the link to the Swing tutorial efrom the topic listing page for this forum and click through to the Layouts section where you can learn how to use GridBagLayout and GridBagConstraints properly.
    As an aside, there is no need to extend JFrame to create a GUI that has to show a JFrame. Favor composition over inheritance. And in this case, it leads to add(...) coode being all over the place where it can't be easily found.
    db

  • Own JDialog - works with java5, doesn't work with java6

    Hello,
    I'm working on map editor for a bigger project and I'm stuck with displaying my own JDialog (grrr...). I found out that problem occurs only with java6. See the screenshots below:
    java5
    http://student.agh.edu.pl/~kdzwinel/Projects/TrafficSim/MapEditor/good.jpg
    java6
    http://student.agh.edu.pl/~kdzwinel/Projects/TrafficSim/MapEditor/wrong.jpg
    And some implementation details:
    how do I create new dialog:
    NewMapDialog dialog = new NewMapDialog(this);
    dialog.setVisible(true);how dialog class looks like:
    public class NewMapDialog extends JDialog implements ActionListener, ChangeListener
         NewMapDialog(Main owner)
              super(owner,"New map",true);
              this.setAlwaysOnTop(true);
              this.setSize(200, 280);
              this.setResizable(false);
              this.setLocationRelativeTo(owner);
              makeLayout();
         private void makeLayout()     
              Container content = getContentPane();
              content.setLayout(new FlowLayout());
    //(...) <- add stuff
    }That is so simple that I'm really confused. I will appreciate some help.
    Regards,
    Konrad
    Edited by: kdzwinel on Feb 5, 2008 6:23 PM

    kdzwinel wrote:
    Hm, creating my applications I extend JFrame, JPanel, JLabel all the time, what is wrong with extending JDialog?In this case your class contained two methods that were already defined to mean something completely different in the class you derived from. That's just one example of what can go wrong when you use inheritance. Had you used composition rather than inheritance (i.e. your class contained a JDialog rather than being a JDialog) this problem would never have happened.
    Such an extension was quite natural for me to use because I was looking for this dialog to be modal. And I guess making JFrame modal is not so trivial.
    You can make a modal JDialog without extending JDialog, so that's not a problem.
    BTW, funny thing is that this 'mistaken' code worked just fine with java5 - I was confused by this fact so my first guess was that I messed something up with panes/layouts.Another reason you should be careful with inheritance: your program may break from implementation changes in the library code you are using and extending. Maybe Java 5 does not use those two methods when it "draws the dialog". Again, had you been using composition your program would not have been affected.
    If you can, get your hands on a copy of "Effective Java" by Joshua Bloch, and read chapter 14 "Favor composition over inheritance". He explains this much better than I can.

  • Gridbag layout problem on a tabbedpane

    I am not sure whether we can do this or not but, I am trying to have a gridbag layout on a TabbedPane object.
    I have a JFrame on which I am adding a TabbedPane object called "t" and on this TabbedPane I am adding a tab called "Insert" which is an object of class "Insert Data". Then, I add the TabbedPane t on the Container cp, which is inside the JFrame.
    In the InsertData Class (a JPanel), I need to have the gridbag layout. With this gridbag layout object, I am trying to place different objects like buttons, at various places, on this JPanel. But nothing moves on this panel.
    In short, please let me know how can I have a gridbag layout on a Tabbedpane.
    The Main Class is as follows:
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import javax.swing.JFrame;
    import javax.swing.JTabbedPane;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class Main extends JFrame implements ActionListener, ChangeListener{
         Main(){
                   setPreferredSize(new Dimension(1200,600));
                   Container cp = getContentPane();
                   JTabbedPane t = new JTabbedPane();
                   // insert
                   InsertData insertOptions = new InsertData();
                   t.addTab("Insert",insertOptions);
                   cp.add(t);
                   this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   pack();
                   setVisible(true);
              @Override
              public void actionPerformed(ActionEvent arg0) {
                   // TODO Auto-generated method stub
              @Override
              public void stateChanged(ChangeEvent arg0) {
                   // TODO Auto-generated method stub
              public static void main(String args[]){
                   new Main();
         }The InsertDataClass is:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class InsertData extends JPanel{
         InsertData(){
              setPreferredSize(new Dimension(1200,600));
              setBackground(Color.blue);
              //setLayout(new GridBagLayout());
              GridBagLayout gb = new GridBagLayout();
              setLayout(gb);
              GridBagConstraints c = new GridBagConstraints();
              //c.insets = new Insets(2, 2, 2, 2);
              //JPanel p1= new JPanel();
              //p1.setPreferredSize(new Dimension(200,200));
              JButton b1 = new JButton("here i am!!!");
              //p1.add(b1);
              //c.fill = GridBagConstraints.HORIZONTAL;
              //c.anchor = GridBagConstraints.WEST;
              c.gridx=0;
              c.gridy=1;
              add(b1,c);
    }

    how can I have a gridbag layout on a Tabbedpane.Huh? You post an example with just one JButton and no weightx / weighty set and you expect others here to be able to see a problem with your layout?
    Also, there's needless, unused code that is just clutter -- like the unimplemented ActionListener and ChaneListener. Recommended reading: [SSCCE (Short, Self Contained, Compilable and Executable, Example Program)|http://mindprod.com/jgloss/sscce.html].
    Finally, I don't see any need whatsoever to extend JFrame and JPanel as you are not introducing any new behavior of either. Always favor composition over inheritance.
    I plugged in some code I had used for someone else's GridBagLayout problems and this will show you that there's no difference in using GridBagLayout in a tabbed pane component or anywhere else.import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import javax.swing.*;
    public class GridBagInTabbedPane {
      public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
            new GridBagInTabbedPane().makeUI();
      public void makeUI() {
        Font fontButton = new Font("Arial", Font.BOLD, 10);
        Font fontLabel = new Font("Arial", Font.BOLD, 15);
        JLabel labelEnter = new JLabel("Enter sentences in the text area ");
        labelEnter.setFont(fontLabel);
        JTextArea textArea = new JTextArea();
        textArea.setPreferredSize(new Dimension(630, 280));
        JScrollPane scrollPane = new JScrollPane(textArea);
        scrollPane.setMinimumSize(new Dimension(630, 280));
        JLabel labelDuplicates = new JLabel("Duplicates will appear here");
        labelDuplicates.setMinimumSize(new Dimension(650, 30));
        labelDuplicates.setFont(fontLabel);
        JButton buttonDisplay = new JButton("Display Map");
        buttonDisplay.setFont(fontButton);
        JButton buttonClear = new JButton("Clear");
        buttonClear.setFont(fontButton);
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        gbc.fill = GridBagConstraints.NONE;
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.weightx = 0.5;
        panel.add(labelEnter, gbc);
        gbc.gridy = 1;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.weighty = 0.5;
        panel.add(scrollPane, gbc);
        gbc.gridy = 2;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weighty = 0.0;
        panel.add(labelDuplicates, gbc);
        gbc.gridy = 3;
        gbc.gridwidth = 1;
        gbc.anchor = GridBagConstraints.EAST;
        panel.add(buttonDisplay, gbc);
        gbc.gridx = 1;
        gbc.anchor = GridBagConstraints.WEST;
        panel.add(buttonClear, gbc);
        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.add(panel);
        JFrame frame = new JFrame();
        frame.add(tabbedPane);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }db

  • Inherit problems

    Dear reader,
    I have a problem. In my first class I have a collection and I need to inherit all it is value's to another class. My code:
    {color:#339966}public class Hattrick extends JPanel implements ActionListener {
    &hellip;
    Collection<Speler> spelers = new ArrayList<Speler>();
    public Collection<Speler> getCollection() {
    return this.spelers;
    &hellip;
    {color}
    And here is the class where the collection needs to be inherit:
    {color:#339966}public class ToolActies extends AbstractAction {
    protected Hattrick hattrick;
    {color}
    {color:#339966}public void actionPerformed(ActionEvent e) {
    Collection<Speler> spelers = hattrick.getCollection();
    &hellip;
    {color}
    But Collection<Speler> spelers = hattrick.getCollection(); give exception
    {color:#339966}Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at ToolActies.actionPerformed(ToolActies.java:30)
    ...{color}
    Anybody has a clue how to inherit the collection? I owe you already
    Greets,
    Vinvar

    This is composition, not inheritance, and you forgot to do something like this:
    public class ToolActies extends AbstractAction {
        private Hattrick hattrick;
        public ToolActies(Hattrick hattrick) {
            this.hattrick = hattrick; //<<<------
    }

  • Extending vs. Using Data Structures

    I'm fairly new to Java, though not to coding in general, and I'm wondering, whether its better to extend a data structure or to use one, when creating a class.
    For example, I've been messing around with some playing cards, and to make the deck, I essentially want to use a stack. Would it be better to create a Deck class that extends Stack, or to create a Deck class that contains a Stack object and methods that modify the Stack? I've tried it both ways, and they both seem to do okay, but I'm wondering which way is preferable.
    So far, inheriting seems more powerful, but using is much cleaner. (e.g. I don't have to worry about them calling pop() instead of draw())
    Edited by: chess19 on Mar 16, 2009 6:19 PM

    You seem to be on track in terms of the issues involved. If you google for the phrase "prefer composition to inheritance" you'll find a lot of people with relevant advice.

  • Program not exiting when dispose() used.

    pl see the code.
    I am unable exit the window if the new class Ex() is defined.
    No error displayed, while running the program. What is the mistake. If anyone see please inform. No compilation error and at runtime, if Exit button is pressed, the window is not getting closed. I want to use dispose() instead of System.exit(0).
    This is because, If I use System.exit(0), my menu program would also get disconnected.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.sql.*;
    import java.io.*;
    class ts extends JFrame
    JPanel jpn1,jpn2,jpn3;
    JButton b1,b2,b3;
    JLabel jlh;
    JFrame fr;
    Container cp;
    Connection con = null;
    Choice ch1,ch2;
    public ts()
    final JFrame jf = new JFrame();
    JPanel jpn1 = new JPanel();
    jpn1.setLayout(null);
    jpn1.setBackground(Color.pink);
    jpn1.setPreferredSize(new Dimension(800,100));
    JPanel jpn2 = new JPanel(new GridLayout(0,1));
    jpn2.setPreferredSize(new Dimension(775,50));
    jpn2.setBackground(Color.cyan);
    jlh = new JLabel("Test Module",JLabel.CENTER);
    jlh.setFont(new Font("TimesRoman",Font.BOLD,25));
    jpn2.add(jlh);
    JPanel jpn3 = new JPanel();
    jpn3.setBackground(Color.yellow);
    jpn3.setPreferredSize(new Dimension(800,50));
    Container cp = jf.getContentPane();
    cp.add(jpn1,BorderLayout.WEST);
    cp.add(jpn2,BorderLayout.NORTH);
    cp.add(jpn3,BorderLayout.SOUTH);
    JButton b1 = new JButton("Get Details");
    b1.setBounds(150,450,100,20);
    jpn1.add(b1);
    JButton b2 = new JButton("Update");
    b2.setBounds(300,450,100,20);
    jpn1.add(b2);
    JButton b3 = new JButton("Exit");
    b3.setBounds(450,450,100,20);
    jpn1.add(b3);
    b3.addActionListener(new Ex());
    /* b3.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    jf.dispose();
    return;
    //System.exit(0);
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jf.setSize(800,700);
    jf.setVisible(true);
    //jf.pack();
    jf.show();
    class Ex implements ActionListener
    public void actionPerformed(ActionEvent evt)
    if(evt.getSource() == b3)
    dispose();
    return;
    public static void main(String[] args)
    new ts();
    }

    Your class both extends JFrame and instantiates a (separate, totally different!) JFrame. You are disposing the wrong JFrame -- and there shouldn't be two anyhow.
    Since you are not modifying any default behavior of JFrame, your class has no reason to subclass JFrame. Always prefer composition over inheritance.
    In future (not this time), Swing questions should be posted in the [Swing forum|http://forums.sun.com/forum.jspa?forumID=57]
    db
    edit And go through the [Swing Tutorial|http://java.sun.com/docs/books/tutorial/uiswing/index.html] which will (hopefully) raise your level of competence. You need more inputs than a forum can provide.
    Edited by: Darryl.Burke

  • HELP NEEDED WITH SOME QUESTIONS

    Could ye guys help, I have some questions and I dont know the answers of them! any solutions would be great
    Distinguish between composition and inheritance as used in object-oriented programming. As part of your answer, provide examples of different situations in which each would be more appropriate.
    What is meant by recursion as an algorithmic strategy in working with abstract data structures, and why is such an approach considered worthwhile? Illustrate your answer with an example sorting algorithm in Java that can be sorted linearly and recursively.
    Given an alphabet of {x,y,z} possessing the following frequency distributions {1/8, 1/4, 5/8}, show how this information may be used to construct a prefix code binary tree. Given the code 11000111100, show how this is decoded using this construct.
    Any ideas??

    086kerry wrote:
    lad if you had seen what I had to do already, its not as if I want the answers, just help. I cant find anything satisfactory on the web.Not to quick are ye?
    If you can't do more than post your assignment and cry for help then you might as well give up now. Nobody is going to do your work for you. You have done NOTHING yet so start working on it and if you run into problems come back with your code and ask questions about it.

  • Must implement specifik interface

    Hi,
    Im creating a game to force myshelf to code a game-engine, just for fun. In this game I have superclass for a basic unit. This class gets subclassed down to game-units. I have different type of game units, some more advanced than others (my game idea is like a manager game where choose between units similar to warcraft 3 units).
    To help the game-engine separate between the different type of units and the methods that can be used on them, I want to use differtent interface for the advanced units. This could be the start of the Wizard-class:
    public class Wizards extends BasicUnit implements SpellCaster {
    // method and variables that are specific for a wizard and dont excist in BasicUnit
    }Question is: How can I force a method in the game-enginge class to look if a used unit implements a certain interface, in this case the SpellCaster-interface?
    I know it should be possible, like the Comparable Interface. But how do i do it?
    If its a dumb question a link to the specifik documents would do, I read it myshelf. But of course I would be happy if someone have the kindness to write an example. Again, this aint homework, just a fun x-mas project for me.

    Ani_Skywalker wrote:
    Hi again Jverd,
    I google [visitor pattern|http://en.wikipedia.org/wiki/Visitor_pattern] and through that I also find [virtual function|http://en.wikipedia.org/wiki/Virtual_functions] . I can see how its usefull in this issue.
    Thought my main concern for the moment is about [composition over inheritance|http://blogs.msdn.com/steverowe/archive/2008/04/28/prefer-composition-over-inheritance.aspxI]. This is not what we learned in school when I took my first and second java courses. But I think the composition over inheritance strategy seems very sensible.
    jverd wrote:
    I don't really know your whole picture, but one option is to define a type that has those particular operations in common, and pass that type around when that's what you need. The subclasses could inherit from a base class that provides those, or implement an interface, and then add their own methods.But this is exactly what my class BasicUnit does. Maybe my english is bad and I misslead you, or maybe I should pick a better name for that class, like Unit. But what it does is to hold methods that every unit in the game use. Subclasses that need more methods adds that. The way you wrote your example is kind of how I've done it, as it seems to me. Could you tell me were you think I do wrong?It may have just been a misunderstanding on my part, as I don't know you and I don't know your requirements or the details of how you're implementing them.
    Or it may be that you're kind of close to doing it correctly, but not quite. The situation I described as a good approach can look a lot like the not-so-good way I thought you were doing it. I'm kind of sleep-deprived right now, so I don't have the energy or brainpower to go into any more detail at the moment.
    Good luck though. I expect somebody will continue helping you if you keep working at it.

Maybe you are looking for