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

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 :-)

  • SRM Roles - Composite versus Single

    Hi Guru's
    I am at the devlopment stage of building roles for an SRM implementation and have been advised to build composite roles as opposed to single roles.
    What are your experiences of composite roles against single roles in SRM ?
    In other modules we have found single roles to be better as they are easier to analyse as far as errors are concerned ,also with the absence of an SU53 type transaction in SRM I would imagine that analysing errors in composite roles will prove more complicated than in single roles.
    Has anyone experience or advice on this issue ?
    Thanks
    Simon

    Hi if you need to do this from  a NON-CUA system  to all other systems in your landscape go to transaction PFCG
    1. Transaction PFCG
    2. Perform mass import of roles  from  other systems to the reference system( or the system you wish to do this analysis)
    3.Click on role tab on the main menu , choose read from other system by RFC
    4. Then You can enter either an RFC destination
    or a variable which points to an RFC destination as target system
    (Define variables in transaction SM30_SSM_RFC).
    5. Now you can follow the instruction as per other Experts instruction ( AGR_AGR ) table
    Follow the above steps if you need to do this for various other SAP systems.
    Basically you are getting all the roles to one central place
    secondly an RFC connection with necessary authorization  is required between each of the systems you are trying to analyze
    Edited by: Franklin Jayasim on Jul 14, 2010 6:54 PM
    Edited by: Franklin Jayasim on Jul 14, 2010 7:15 PM

  • Composite versus Surrogate PK

    I am in the middle of assisting developing a new db and due to the nature of the data and business rules and replication, we have entered into discussion on types of PKs. We will be using 9i at the central database (CDB) and local transaction server (LTC) and 9iLite at the work station.
    We have a need to include the workstation id with the primary key (auto numbered) to allow uniqueness when the workstation is combined with others at the LTC and CDB.
    Model is
    person (person_id (auto number) as PK)
    detail: main_trans ( workstation PK, trans_id PK (autonumber) and person_id FK)
    detail to main_trans: applications (app_id PK (autonum) trans_id FK and workstation FK and person_id FK
    Several questions:
    1. Can Oracle9i support FK based on the PK composite?
    2. Should this model (very briefly explained) use surrogate with the composite PK?
    Thanks

    I find that in general composite keys built on business data work better than artificial keys. Due to business rules when generated keys are used you generally end up needing to build the PK on the generated key and another unique index on the business information to support the business requirements. With the composite key only one index is needed instead of 2.
    Then in order to access data using the generated key you have to go to the parent table when in many cases the query only needs information from the child based on the values of the natural key. So now extra work has to be done to access the data.
    Both types of keys have their place. The choice depends on the data, how it will be accessed, and how it relates to other data in the application.
    IMHO -- Mark D Powell --

  • 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

  • Interfaces to replace multiple inheritence

    Howdy,
    I have, conceptually, the following situation: I have a Ball abstract class. The Ball has several
    concrete methods. It also has an abstract method getAppearance (that would somehow return how a
    Ball is visualized). I have several "adjective" subclasses that I would like to build from it, for example:
    SpikyBall, GlowingBall, ColorBall, etc. I would like these classes to be concrete.
    Additionally, I would like to have a concrete class of any permutation of this list of adjectives, for example:
    SpikyColorBall, GlowingColorBall, SpikyGlowingColorBall. I want to accomplish this
    using as little code rewriting as possible, and, hopefully, none at all.
    Using certain other single letter languages that I won't name here, I used Multiple Inheritence. A
    SpikyColorBall would inherit from both SpikyBall and ColorBall, who both inherited from
    Ball. I was told I could accomplish this in Java using interfaces instead of multiple inheritence, which
    Java doesn't support. How is this accomplished? Could you give me (or forward me to) a good
    example? Again, the power I'm looking for is multiple inheritence's code-reusability.
    As a side note, why did Java choose to use interfaces instead of multiple inheritence?

    Courtesy of yawmark...
    composition_v_inheritance
    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.

Maybe you are looking for

  • Listing a join column only once in a select

    Hi.  Has there been any advancement in t-sql where I can continue to select * on tables a and b in a join but expect to get back only one occurrence of columns that r used in the join.  Or do I still need to explicitly list all cols in the query? eg.

  • Unable to release OPM Batch in R12

    Hi gurus, We are implementing R12 OPM and using the shared version of unconstrained ASCP planning. We are not able to release OPM batch planned orders to OPM execution. The profile Auto Implement planning suggestion to APS is set as No and ran the "A

  • IDOC ATTRIBUTE_WRONG_INTF

    Hi I got the following the error message: <!--  Call Adapter   --> - <SAP:Error xmlns:SAP="http://sap.com/xi/XI/Message/30" xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/" SOAP:mustUnderstand="">   <SAP:Category>XIAdapter</SAP:Category>   <SAP

  • Is there a limit to the number of airport extremes and airport expresses one should have in a network?

    Is there a practical limit to the number of airport extreme base stations and airport express units one should have in a home network?

  • Wrong back up with refurbished phone

    I had to purchase a refurbished phone last week because of a dead battery. I had backed up all my information to ITunes before I took it in. Somehow the wrong back up is on this phone now. I went into the files and can see the back up I created on th