Design question on extending a class

Hi all,
I'm working on a team project where we've decided to customize many JComponents for our GUI. We're also extending the models for their respective JComponents. For example, a CustomJTextField (sublass of JTextField) has a CustomDocument (subclass of PlainDocument) as its model.
My question is this: is it a preferred OO practice (or not) to delegate the methods of CustomDocument to CustomJTextField, given that it's already understood that a CustomJTextField has a CustomDocument as its model by default. An example:
without delegation:
CustomJTextField text = new CustomJTextField();
// 1. get the model
// 2. determine if it is the type you're expecting
// 3. if so, cast it and use it
if (text.getModel() instanceof CustomDocument)
  ((CustomDocument)text.getModel()).doSomeCustomThing();
}with delegation:
CustomJTextField text = new CustomJTextField();
// 1. just ask the componet to do the work
text.doSomeCustomThing();The second form seems much cleaner, but the argument is that it would be a lot of work to delegate every method of the model to the component, and then have to maintain the delegate methods as well as the model's methods.
To me, it seems as if I'd rather have more work in one place (the subclassed JComponent) rather than having it spread all throughout the code. Also, isn't calling "getModel()" everywhere considered bad practice? Should a developer using a component even know (or care) what kind of model it has?
Even though the delegation methods seems to me that is makes the custom components easier to use, I haven't found any written examples (in books or online) of this being done anywhere. All of the examples are directly accessing the model of the component.
Any thoughts? I'm new to OO programming (as you might have guessed), so be gentle with me.
Thanks.

Precisely my intentions. So to reword the question -
is this a bad practice? My feeling is that a
developer using a CustomJTextField should expect some
"extra" behavior (in this case, that of a
CustomDocument) or else they'd just be using a plain
old JTextField instead. Bad assumption?Well, I guess that would depend on the custom behaviour. If the customization is to limit the field to only accept certain characters (like numbers only or a limited amount of text), then, as a Swing user, I would expect this behaviour to be handled via a custom Document. I would just say, hey, I need to put a zip code field, so I'll just make a JTextField and give it a ZipCodeDocument. getText() is going to work the same no matter what.
Another example would be if I have an IP address field. I would create an IPAddressDocument, which does validation of the data entered to prevent invalid octet values and maintain formatting. Now, getText() is going to return a string, but I might want to have a special method in the document class to return a java.net.InetAddress object as a convenience method. I suppose one could subclass JTextField as well to make IPAddressField and add a delegate method, but I'm not sure I would do that.
But I'm not clear on what these customizations are, so it's hard to say what's best for your situation. I really don't see a problem with either, though, if that's the consensus between you and your associates.
if you are writing Swing components and models,
I would expect that it follows certain patterns thatthe
rest of the Swing components useKnow of any good books, articles, etc. on this?
Everything I've read talks about extending the
JComponents, or extending the models, or extending
the renderers, etc. but always as separate exercises
and never where it's all going on at once. Even
then, the examples are usually just that, a way to
show how it works, not necessarily what the best way
to do it is.No, I don't know of any good books. They talk about extending JComponent mostly in reference to creating specialized components that are generally different from those provided. The extending models and renderers has to do with the general assumption that if you want a tree component, then JTree already gives you all you need... The customizations will be things like how do the nodes display (renderer) and where do the nodes come from (model). There's not really any link between those, though. The renderer can just be assume to be independant. Here's a node, how do I want to display it? Text, and icon, different color when selected?
>
Also, the more I read about MVC, the more confused I
am about it. Everyone seems to have different
interpretations as to the roles of each part, how each
part should interact with each other, etc. I haven't
seen anything on MVC "patterns" (as it applies to
Swing).If you haven't read this, maybe it'll shed some light...
http://java.sun.com/products/jfc/tsc/articles/getting_started/index.html

Similar Messages

  • Extending WebCatItemList class

    Hi
    I have a functionality to implement in CRM ISA 4.0 in which I need to filter out WebCatItem object stored in form of arraylist in class WebCatItemList.
    I tried extending the class WebCatItemList but it didn't help.
    All I want is, based on a few attributes of some items (WebCatItem) in WebCatItemList, I want to filter some items that suits my requirement. For example if the description of an item contains "ABC", I want to keep it otherwise discard from the WebCatItemList object. If anybody has done something of the sort, please let me know. I'll be really grateful.
    Cheers
    Pankaj Bansal

    Hi,-
    i have a question regarding extending a class.
    what is wrong with the following statement?
    sub_class a = (sub_class) class.method();
    sub_class is an extension of class.
    thanks,
    barisI'm afraid without any actual code, all I can say is that you tried to cast the reference that method returned to something that it is not a subclass of. This is per the docs for ClassCastException which say, in part:
    (your) code has attempted to cast an object to a subclass of which it is not an instance.

  • Extending XMLSocket class

    I'm using Flash MX 2004. I want to write a class that extends
    XMLSocket and provides a little more information. For instance, I
    want *my* socket class to have a property that indicates whether
    the socket is connected or not and I want the Boolean value of
    'connected' to be set when the socket's onConnect event triggers.
    How do I modify/capture the super class's events? Perhaps someone
    can recommend how I might change my class:

    Hi,-
    i have a question regarding extending a class.
    what is wrong with the following statement?
    sub_class a = (sub_class) class.method();
    sub_class is an extension of class.
    thanks,
    barisI'm afraid without any actual code, all I can say is that you tried to cast the reference that method returned to something that it is not a subclass of. This is per the docs for ClassCastException which say, in part:
    (your) code has attempted to cast an object to a subclass of which it is not an instance.

  • Design question about when to use inner classes for models

    This is a general design question about when to use inner classes or separate classes when dealing with table models and such. Typically I'd want to have everything related to a table within one classes, but looking at some tutorials that teach how to add a button to a table I'm finding that you have to implement quite a sophisticated tablemodel which, if nothing else, is somewhat unweildy to put as an inner class.
    The tutorial I'm following in particular is this one:
    http://www.devx.com/getHelpOn/10MinuteSolution/20425
    I was just wondering if somebody can give me their personal opinion as to when they would place that abstracttablemodel into a separate class and when they would just have it as an inner class. I guess re-usability is one consideration, but just wanted to get some good design suggestions.

    It's funny that you mention that because I was comparing how the example I linked to above creates a usable button in the table and how you implemented it in another thread where you used a ButtonColumn object. I was trying to compare both implementations, but being a newbie at this, they seemed entirely different from each other. The way I understand it with the example above is that it creates a TableRenderer which should be able to render any component object, then it sets the defaultRenderer to the default and JButton.Class' renderer to that custom renderer. I don't totally understand your design in the thread
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=680674
    quite yet, but it's implemented in quite a bit different way. Like I was saying the buttonClass that you created seem to be creating an object of which function I don't quite see. It looks more like a method, but I'm still trying to see how you did it, since it obviously worked.
    Man adding a button to a table is much more difficult than I imagined.
    Message was edited by:
    deadseasquirrels

  • Design question:  How to double extend?

    I know that extending two classes cannot be done, so is there a work around?
    I have two classes: Class_A, Class_B.
    I want all the methods within both of the classes to be usable in Class_C
    So I want: Class_C extends Class_A, Class_B.
    Thanks for any advice

    I am grateful for everyone's help.
    Sorry, maybe that was a bad example. Here is what I am doing, and I do not know the best way to implement it.
    I have a big canvas, and different collection objects can be added to it.
    I have 4 base collections: Memory, Subset, Selectable, Non-Selectable
                  BaseCollection
       Memory   Subset   Selectable   Non-SelectI want a SelectableMemoryObject...
    Below example I have to re-write Select & Non-Select methods over and over again:
                          Base
           Memory                    Subset
    MemSelect MemNonSelect     SubSelect SubNonSelectBelow example I have to re-write Memory & Subset methods over and over again:
                          Base
           Select                    Non-Select
    MemSelect MemNonSelect     SubSelect SubNonSelectHere is a case where I would want multiple inheritance. Once again, I appreciate the help.

  • Question abput Extending Classes

    Hi,
    Would anyone know if the following is valid??
    class A extends B{}
    class B extends A{}
    Thanks in advance...

    It is a cyclic inheritance error if a class or interface inherits from itself, even directly (i.e., it appears as its super-class or in its list of super-interfaces) or indirectly (i.e, one of its super-class or one of its super-interfaces inherits from it)A cyclic inheritance error is reported

  • Database Connection design question

    Hello, I have a design question. Awhile back I needed to create a database connection to SQL Server, so I created a class to do it
    import java.sql.*;
    import java.io.*;
    import java.net.MalformedURLException;
    import org.w3c.dom.Document;
    import org.w3c.dom.*;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    public class SQLServerConnection
         private static Connection connection = null;
         public SQLServerConnection(String user, String password, String dbName) throws java.sql.SQLException
              getDBConnection(user, password, dbName);
         public SQLServerConnection(String configFileName) throws java.sql.SQLException
              getDBConnection(configFileName);
         private void getDBConnection(String user, String password, String dbName) throws java.sql.SQLException
             DriverManager.registerDriver(new com.microsoft.jdbc.sqlserver.SQLServerDriver());
             connection = DriverManager.getConnection(
                  "jdbc:microsoft:sqlserver:" + dbName, user, password);              
         private void getDBConnection(String configFileName) throws java.sql.SQLException
              String user;
              String password;
              String dbName;
              try
                   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                   DocumentBuilder db = factory.newDocumentBuilder();
                   Document doc = db.parse(configFileName);
                   doc.getDocumentElement().normalize();
                   // get the configuration information
                   password = getConfigParameter("password", doc);
                   user = getConfigParameter("username", doc);
                   dbName = getConfigParameter("databasename", doc);
                   getDBConnection(user, password, dbName);
              catch (MalformedURLException murle)
                   System.out.println("Unable to connect to: " + configFileName + " -- " + murle);
                   System.exit(1);
              catch (FileNotFoundException fnfe)
                   System.out.println("Configuration file " + configFileName + " not found.");
                   System.exit(1);
              catch (IOException ioe)
                   System.out.println("IOException: " + ioe);
                   System.exit(1);
              catch (javax.xml.parsers.ParserConfigurationException pce)
                   System.out.println ("Parser Configuration Error: " + pce);
              catch (SAXException saxe)
                   System.out.println ("SAXException: " + saxe);
         private String getConfigParameter(String paramName, org.w3c.dom.Document doc)
              NodeList nl = doc.getElementsByTagName(paramName);
              if(nl != null)
                   Node n = null;
                   for (int i = 0; i < nl.getLength(); i++)
                        n = nl.item(i);          
                        if(n.hasChildNodes())
                             NodeList children = n.getChildNodes();
                             return ((Node)children.item(0)).getNodeValue();
              else
                   System.out.println ("nl is null");
              return "";          
         public void setCatalog(String catalogName) throws java.sql.SQLException
              connection.setCatalog(catalogName);
         public Connection getConnection()
              return connection;
         public void closeConnection()
              try
                   connection.close();
              catch(java.sql.SQLException sqle)
                   System.err.println ("SQL Server Connection failed to close: " + sqle);
    }Later on, I needed to do the same thing for MySQL, so I created a class for that, MySQLServerConnection which is exactly the same as above, except for:
    private void getDBConnection(String user, String password, String dbName) throws java.sql.SQLException
              try
                   Class.forName("com.mysql.jdbc.Driver").newInstance();
                   connection = DriverManager.getConnection(dbName, user, password);     
              catch(java.lang.ClassNotFoundException cnfe)
                   System.out.println (cnfe);
              catch(java.lang.InstantiationException ie)
                   System.out.println (ie);
              catch(java.lang.IllegalAccessException iae)
                   System.out.println (iae);
         }Later, on, I did the same thing with OracleServerConnection. My question is, I know this is probably not optimal code. For example, I didn't originally have a close connection method, so I had to go in and code one for all 3. I'm assuming that an interface would be a good idea so that if I have to code another database connection class I make sure and include all of the appropriate methods. I'm also assuming that it would have been smart to have a master class, maybe something like DatabaseConnection and extended these classes from that. Am I on the right track? Totally offbase?

    @nclow - I will work on trying the Factory Pattern for this over the weekend and post when I finish to see what you think.
    @abillconsl - just to make sure I understand, you're saying that I just try to connect and it will cycle through the different database connection possibilities and connect when it finds the right one? If it fails all 3, log an appropriate message. One question I have about this is, I thought I was being object oriented by separating the different types of db connections (Oracle, SQL Server, MySql) into different classes. Am I missing the point of OOP by what I was/am trying to accomplish? Going overboard? Also, does your way try and connect to all 3 even if I connected to one already?
    Thx, Grantarchy
    Edited by: grantarchy on May 9, 2008 9:50 PM

  • Design Question: Parent/Child Distribution

    Hi,
    I have what I think is a straightforward design question. I tried
    searching this forum for the answer, but struggled with what keywords
    to use in the searches. (I also struggled with what to put on the
    subject line for this post!)
    Anyhow, here is my question: Given:
    public class Pet {...}
    public class Dog extends Pet {...}
    public class Cat extends Pet {...}
    public class Pig extends Pet {...}
    Which is the better design?
    DESIGN A:
    public abstract class PetOwner {
    private Pet pet;
    PetOwner(Pet pet) {
    this.pet = pet;
    public Pet getPet() { return this.pet; }
    public class DogOwner extends PetOwner {
    public DogOwner(Dog dog) {
    super(dog);
    public class CatOwner extends PetOwner {
    public CatOwner(Cat cat) {
    super(cat);
    public class PigOwner extends PetOwner {
    public PigOwner(Pig pig) {
    super(pig);
    ===============================================
    or DESIGN B:
    public abstract class PetOwner {
    PetOwner() {
    public class DogOwner extends PetOwner {
    private Dog dog;
    public DogOwner(Dog dog) {
    super();
    this.dog = dog;
    public class CatOwner extends PetOwner {
    private Cat cat;
    public CatOwner(Cat cat) {
    super();
    this.cat = cat;
    public class PigOwner extends PetOwner {
    private Pig pig;
    public PigOwner(Pig pig) {
    super();
    this.pig = pig;
    This is a somewhat contrived example, so don't take it too literally.
    My question is where should I put the field that holds a Pet object?
    All pet owners own a pet, so should I put it in the parent class
    (Design A)? Note the constructors for the child classes (e.g.
    DogOwner) are designed so that the correct type of pet is checked
    for. Or should each child class hold its own type of pet (Design B)?
    If the answer is "it depends" (as I suspect it is), then what are
    the questions I should be asking myself in order to decide?
    Thanks very much, in advance!!
    Chris

    eg,
    import java.util.*;
    class Pet {
        private String name = null;
        public Pet( String n ) {
         this.name = n;
        public String toString() {
         return name;
    class Dog extends Pet {
        public Dog( String n ) {
         super( n );
    class Pig extends Pet {
        public Pig( String n ) {
         super( n );
    class Cat extends Pet {
        public Cat( String n ) {
         super( n );
    class PetOwner {
        private Vector pets = new Vector();
        private int dogs = 0;
        private int cats = 0;
        private int pigs = 0;
        public void add( Dog d ) {
         pets.add( d );
         dogs++;
        public void add( Cat c ) {
         pets.add( c );
         cats++;
        public void add( Pig p ) {
         pets.add( p );
         pigs++;
        public boolean isCatOwner() {
         return cats > 0;
        public boolean isDogOwner() {
         return dogs > 0;
        public boolean isPigOwner() {
         return pigs > 0;
        public int numberOfPets() {
         return pets.size();
        public String toString() {
         String s = "";
         Enumeration en = pets.elements();
         while( en.hasMoreElements() ) {
             Pet pp = (Pet) en.nextElement();
             s += pp.toString() + "\n";
         return s;
    public class Pets {
        private PetOwner po = new PetOwner();
        public Pets() {
         po.add( new Dog( "doggy" ) );
         po.add( new Cat( "catty" ) );
        public String toString() {
         String s = "";
         s += po.toString();
         s += po.isDogOwner() + "\n";
         s += po.isPigOwner() + "\n";
         s += po.isCatOwner() + "\n";
         s += po.numberOfPets();
         return s;
        public static void main( String[] args ) {
         Pets p = new Pets();
         System.out.println( p );
    }

  • Design question: Link data between JFrames

    Dear all,
    I have a design question. I have this form in a JFrame where you can set an icon as a property. To achieve this, I have a "Set" button on the form which will open a new window with all the available icons. When you click an icon, I want the "icon" frame to be closed and the selected icon to be send to the original form. This is the way I do it now:
    Interface :
    public interface IconUpdate
    public void updateIcon(Icon icon);
    }Main frame with the "Set" button:
    public class Test extends JFrame implements IconUpdate, ActionListener
        private Icon icon = null;
        public Test()
            // add button and actionlistener and that kind of stuff
        public void actionPerformed(ActionEvent e)
            if(e.getSource() == btnSetIcon)
                new IconFrame(this);
        public void updateIcon(Icon icon)
            this.icon = icon;
    }The Icon frame:
    public class IconFrame extends JFrame implements ActionListener
        IconUpdate parent = null;
        public IconFrame(IconUpdate parent)
            this.parent = parent;
            // Initialize table,"Pick" button etc.
        public void actionPerformed(ActionEvent e)
            if(e.getSource() == btnPick)
                parent.updateIcon((Icon)list.getSelectedValue());
                this.dispose();
    }Maybe I made some spelling faults, but this is the way I implement it. Now my question is: is there another way to achieve my goal? If I have to create an interface for every "popup choose dialog" in my program, I have to create many of them. I know using a combobox in the main frame is an option, but I just want to use it this way. Can anyone tell me how I can rewrite this code to make it better / more professional?
    Tx in advance!!!
    Peter

    I can think of a couple options:
    1) Let IconFrame's constructor accept a Test parameter, instead of creating an interface.
    2) Make IconFrame into a modal dialog & have it store the user's selection in a variable. Then when you show the dialog, your action listener will block until the user selects an icon. Then you can call "getSelectedIcon()" to retrieve his/her selection. This would be much like the JOptionPane.showXXX() methods, and probably the cleaner solution.

  • Design question: Scheduling a Variable-timeslot Resource

    I originally posted this in general java programming, because this seemed like a more high-level design descussion. But now I see some class design questions. Please excuse me if this thread does not belong here (this is my first time using the forum, save answering a couple questions).
    Forum,
    I am having trouble determining a data structure and applicable algorithm (actually, even more general than the data structure -- the general design to use) for holding a modifiable (but more heavily read/queried than updated), variable-timeslot schedule for a given resource. Here's the situation:
    Let's, for explanation purposes, say we're scheduling a school. The school has many resources. A resource is anything that can be reserved for a given event: classroom, gym, basketball, teacher, janitor, etc.
    Ok, so maybe the school deal isn't the best example. Let's assume, for the sake of explanation, that classes can be any amount of time in length: 50 minutes, 127 minutes, 4 hours, 3 seconds, etc.
    Now, the school has a base operation schedule, e.g. they're open from 8am to 5pm MTWRF and 10am to 2pm on saturday and sunday. Events in the school can only occur during these times, obviously.
    Then, each resource has its own base operation schedule, e.g. the gym is open from noon to 5pm MTWRF and noon to 2pm on sat. and sun. The default base operation schedule for any resource is the school which "owns" the resource.
    But then there are exceptions to the base operation schedule. The school (and therefore all its resources) are closed on holidays. The gym is closed on the third friday of every month for maintenance, or something like that. There are also exceptions to the available schedule due to reservations. I've implemented reservations as exceptions with a different status code to simplify things a little bit: because the basic idea is that an exception is either an addition to or removal from the scheduleable times of that resource. Each exception (reservation, closed for maintenance, etc) can be an (effectively) unrestricted amount of time.
    Ok, enough set up. Somehow I need to be able to "flatten" all this information into a schedule that I can display to the user, query against, and update.
    The issue is complicated more by recurring events, but I think I have that handled already and can make a recurring event be transparent from the application point of view. I just need to figure out how to represent this.
    This is my current idea, and I don't like it at all:
    A TimeSlot object, holding a beginning date and ending date. A data structure that holds list of TimeSlot objects in order by date. I'd probably also hold an index of some sort that maps some constant span of time to a general area in the data structure where times around there can be found, so I avoid O(n) time searching for a given time to find whether or not it is open.
    I don't like this idea, because it requires me to call getBeginningDate() and getEndDate() for every single time slot I search.
    Anyone have any ideas?

    If I am correct, your requirement is to display a schedule, showing the occupancy of a resource (open/closed/used/free and other kind of information) on a time line.
    I do not say that your design is incorrect. What I state below is strictly my views and should be treated that way.
    I would not go by time-slot, instead, I would go by resource, for instance the gym, the class rooms (identified accordingly), the swimming pool etc. are all resources. Therefore (for the requirements you have specified), I would create a class, lets say "Resource" to represent all the resources. I would recommend two attributes at this stage ("name" & "identifier").
    The primary attribute of interest in this case would be a date (starting at 00:00hrs and ending at 24:00hrs.), a span of 24hrs broken to the smallest unit of a minute (seconds really are not very practical here).
    I would next encapsulate the availability factor, which represents the concept of availability in a class, for instance "AvailabilityStatus". The recommended attributes would be "date" and "status".
    You have mentioned different status, for instance, available, booked, closed, under-maintainance etc. Each of these is a category. Let us say, numbered from 0 to n (where n<128).
    The "date" attribute could be a java.util.Date object, representing a date. The "status", is byte array of 1440 elements (one element for each minute of the day). Each element of the byte array is populated by the number designation of the status (i.e, 0,1,2...n etc.), where the numbers represent the status of the minute.
    The "Resource" class would carry an attribute of "resourceStatus", an ordered vector of "ResourceStatus" objects.
    The object (all the objects) could be populated manually at any time, or the entire process could be automated (that is a separate area).
    The problem of representation is over. You could add any number of resources as well as any number of status categories.
    This is a simple solution, I do not address the issues of querying this information and rendering the actual schedule, which I believe is straight forward enough.
    It is recognized that there are scope for optimizations/design rationalization here, however, this is a simple and effective enough solution.
    regards
    [email protected]

  • Question Re: Extending AbstractList

    Hi,
    I'm trying to create a custom collection class (MyList) which functions similarly to a LinkedList and will contain elements of MyClass but where I can override the add(), remove() and get() methods. Rather than having those methods operate on the position of the element in the list I want them to function by examining a specific value of each MyClass element (using a for each loop and MyClass.getId() for example). I would also make add() check for duplicate ID's before adding a new MyClass to the list. Additionally, I'd like maintain the for each looping ability of a list externally so from MyOtherClass I can loop on MyList directly. Anyway, my research led me to conclude that extending AbstractList was the approach I needed to take, although I've listed other alternatives that occurred to me below.
    There are a couple of things I'm confused about though and I'm having a hard time find answers to these specific questions.
    1. Do I need a instance variable which will hold the items in my list? For example, do I need to have an ArrayList<MyClass> or LinkedList<MyClass> internally in MyList? If so, I'm confused on how to make the for (MyClass myClass : MyList) loop work.
    2. If I don't have the above, what's the proper way to implement the size() method?
    3. This is my class declaration...it works but it feels wrong...is it actually the correct way to do it?
    public class MyList extends AbstractList<MyClass>4. I'm using this class as a singleton using what I read was a thread safe method (code follows). Are there additional considerations I need to make for the overridden methods or the class declaration? I'm using a public static final instance variable like this:
    public final static MyList INSTANCE = new MyList();And then accessing it like this:
    MyList myList = MyList.INSTANCE;Probably overly complicated but I need to make sure my app is only ever using one list. Anyway, I've tried very hard to find some examples but no joy. In the end I think I have 3 choices:
    1. Copy LinkedList and change the methods I need. For some reason that feels like major overkill. I'm willing to do it if it's the best way though.
    2. I could extend LinkedList but that presents a couple of problems also. First, it's not a good idea to extend concrete classes (or so I read) and second, I can't then override the add method which is the whole point.
    3. The last alternative my limited brain power can come up with, but which makes me lose the for each looping I think, is to just make a non-extending class and manipulate an internal LinkedList. I also lose the ability to have my parameter be a List instead of MyList.
    While I could probably force any of the above to work I'm trying to bend my brain, learn something new, and come up with an elegant solution. Any feedback or advice is appreciated.
    Thanks,
    Pablo

    You can do that. Do you intend to modify the set from multiple threads, or create it in one thread and iterate over it in multiple others?Yes, items can be added and removed from multiple threads, as well as updated.
    I don't recall you saying that. It sounds like you might actually want a SortedMap.True, I didn't explicitly state that, but I believe I did imply it by saying I wanted to override add(), get() and remove() to use the id.
    I have no idea what you mean by that first bit. Do you mean you want a single iterator used by multiple threads, as opposed to multiple threads each having their own iterator?Sorry, I have a hard time explaining myself when trying to learn something new I guess. Yes, multiple threads will need their own iterator I believe. There is a display table showing various properties of each item, then there are currently two different processes which poll the list for specific statuses of each item (like ReadyToSend or Pending) and do independent tasks. These processes are based on a single abstract class since they are both web service clients but with different request/response implementations. My thought was that each of these processes (3 so far) would need their own iterator or possibly their own subsets from the master list based on status. I haven't gotten that far so I don't know. Another process is checking for newly submitted requests which come from an external system via files. It parses the file, stores the object values in the database, and then adds the item to the list. Rather than adding the item directly I was going to pass only the item ID to the add() method and use the factory class I've already created to create a new item from the database to add to the list. This is to pick up valid timestamp values from the record (they're inserted using CURRENT_TIMESTAMP rather than Timestamp objects). The alternative was to store the item and then read it back again. That seemed less elegant. This is the only process doing adds. The ID is actually an externally derived number which is supposed to always be unique but there's nothing to prevent a duplicate. I planned on using the list to control duplicates. If a duplicate is added it's status would be changed in the database to indicate that and it would not be added to the list.
    [Clarification] While the list itself will be accessed from multiple locations, I don't expect any individual item to be accessed simultaneously. I have a feeling that's an important distinction. The processes reading and modifying each item will be working on specific their own specific item status.
    A lot of this is still roughed out only and needs more refactoring. I started the refactoring by working on the list first. I was passing around an open ResultSet which I know is bad but it allowed me to flesh out the rest more quickly. Good idea or not it's what I did.
    Anyway, there would seem to be multiple classes needing access to the list for multiple reasons and yet the list needs singularity to prevent duplicate tasking. I didn't want to get into having to remove the item from one list and add it to a different one when the status changed. I figured the easiest thing to do was have a master list class of some type and have all the various classes use that as a singleton.
    Sorry, not a very succinct explanation I guess but we weren't getting far with me beating around the bush with abstract MyXXX examples. Does this change your thoughts on my implementation idea?
    Read that chapter of Effective Java. If the chapter you're referring to is Chapter 3, I finally found it and I will read it. There is also a Chapter 5 which deals with Generics but doesn't have any mention of equals() which I'm reading also. And, I ordered the book. ;-)
    The bottom line is I still don't understand how I can have a single instance of a TreeMap or SortedMap or MapOfNarnia without having a class to contain it and offer it to calling classes. I realize this is probably a stupid question, but exactly how would I do that without doing something like my last MyClasses example?
    Unfortunately I don't have an infinite amount of time to finish this project so I may have to go with a less elegant solution than I hoped. I'm still learning generics and collections and it's obvious I've got quite a bit to learn before I can use them effectively. That being said, which of my bad ideas is the least bad?
    By the way, I just want to say I really do appreciate the effort all you experts put into to answering questions for us newbs. I realize it's a significant investment of your time and I appreciate it.
    Edited by: Pablo_Vadear on Dec 24, 2009 5:14 AM

  • Design question for database connection in multithreaded socket-server

    Dear community,
    I am programming a multithreaded socket server. The server creates a new thread for each connection.
    The threads and several objects witch are instanced by each thread have to access database-connectivity. Therefore I implemented factory class which administer database connection in a pool. At this point I have a design question.
    How should I access the connections from the threads? There are two options:
    a) Should I implement in my server class a new method like "getDatabaseConnection" which calls the factory class and returns a pooled connection to the database? In this case each object has to know the server-object and have to call this method in order to get a database connection. That could become very complex as I have to safe a instance of the server object in each object ...
    b) Should I develop a static method in my factory class so that each thread could get a database connection by calling the static method of the factory?
    Thank you very much for your answer!
    Kind regards,
    Dak
    Message was edited by:
    dakger

    So your suggestion is to use a static method from a
    central class. But those static-methods are not realy
    object oriented, are they?There's only one static method, and that's getInstance
    If I use singleton pattern, I only create one
    instance of the database pooling class in order to
    cionfigure it (driver, access data to database and so
    on). The threads use than a static method of this
    class to get database connection?They use a static method to get the pool instance, getConnection is not static.
    Kaj

  • Searching for extended ABAP Classes documentation

    Hi,
    I'm a newbie to this forum (perhaps I'm a newbie in an abap too - with my 1.5 yrs abaping) but I'm interested in a few topics related to classes available in the repository:
    1. Where can I find full and detailed info (means description of interfaces both public and private/static) on classes included in a dev.class SLIS, SCET, especially specific ones - currently I'm looking for a documentation on class <cl_alv_changed_data_protocol>, because the info supplied in the repository is not so obviously clear for me.
    2. Can someone point me to a SAP cource/academy -name(s) related to the public classes related to a gui programming and!!!! their support-classes (such as mentioned one above) - which is most important.
    3. (specific question) In the OO framework(s) I worked with in my background there was a possibility to 'extend' some class' behaviour (usualy adding interface). Is there any possibility in a SAP environment to do this and if yes where can I find a docu/info on how to achieve this? Is this achieved only with a related access key?
    4. Please could someone provide me a dev.class names with demo-programs (such as SLIS, SCET) related (mostly) to a GUI-programming?
    Perhaps checking the source of the demo-reports supplied in these dev.classes would help me, but occasionaly it's a bit more complicated and time-consuming than to check a related docu, isn't it?
    The info-sources I have (and used widely) are:
    a) html-documentation with my (ok, our) installation > 4.6C (both integrated into an environment and CHM-help).
    b) 'Controls Technology - Workbench edition' - which I would recommend to all the programmers interested in this area.
    c) 'An Easy Reference for ALV Grid Control'  by Serdar SIMSEKLER (BTW, thank you very, very much Serdar! for providing this reference to the public, I found it very usefull)
    d) of cource, the Class Builder via Repository Browser (se80) which usually and unfortunately doesn't report me any class information when asked.
    e) occasionaly google-ing the world with a specific question and checking this fourm or some related one(s) in the sap community and in de.alt.comp.sap-r3 newsgroup (unfortunately for me the last one is basicaly with postings in German, which makes it unusable to me).
    Perhaps most of you would agree there is a lack of information on these topics. Or, of course, I'm still a newbie and don't know how/where to find it
    Please note, answers in sort of 'Feel free to ask with a specific question here...' are not the answer(s) I'm looking for I know this possiblilty and am using it :-).
    Finaly, one question off topic and related mostly to the moderators:
    Is there an intention or even better a possibility to achieve this forum via NNTP-protocol (means using a standard news-client)? It would be great for me if it's possible or is intended to become possible - I'm using a news-client to track few newsgroups (forums) and it would be great not to switch to a different browser to track this one, which is IMHO the best english-speaking abap-related forum.
    Many thanks in advance.
    Best Regards,
    Ivaylo Mutafchiev
    BC Consultant - Abap developer
    VBS Ltd.
    Varna. Bulgaria
    Message was edited by: Ivaylo Mutafchiev

    From within SE80 choose menu Environment->Controls Examples.  This will lead you to many fine Enjoy Control Example programs.
    Also SAP had a class several years ago called BC412 ABAP Dialog Programming Using EnjoySAP Controls.  It might still be around in some format.

  • Question  about Abstract,Final Class

    when we are using final keyword along with class definition .we are making that class final, means we can’t extend that class. The same thing happens when we make our constructors private. From usability perspective both are same ? or is there any difference?
    Secondly accounting to java syntax a class can be either final or abstract and not both .Then why language specification doesn't impose any restriction on making abstract classes constructor private. We can create an Abstract class with private Constructor (Basically utility class with all methods are static) ,to make this class Singleton .This situation is equal to abstract final class ?
    Thanks,
    Paul.

    EJP wrote:
    when we are using final keyword along with class definition .we are making that class final, means we can’t extend that class. The same thing happens when we make our constructors private.No it doesn't.
    Secondly accounting to java syntax a class can be either final or abstract and not both.Correct.
    Then why language specification doesn't impose any restriction on making abstract classes constructor private.Why should it? That proposition doesn't follow from your previous sentence.I think OP is asking about this case
    public abstract class WTF {
      private WTF() {}
      private WTF(...) {}
    }where the class is abstract and all the c'tors are final. It's an abstract class that cannot be extended, much like a final abstract class would be if it were allowed. So, since purpose of abstract classes is to be extended, the OP seems to be asking, "Why can we, in this fashion, create an abstract class that cannot be extended?"
    I don't know the answer to that, but I would guess that, while final is an explicit syntactical element for the purpose of making a class non-extensible, in the all-private-c'tors case, the non-extensibility is simply a side effect, and probably enough of a corner case that it wasn't worth the effort to explicitly forbid it in the spec.
    I also think it's something not worth thinking much about. It was certainly not a key point of some grand design.

  • Extending abstract classes

    I just have a simple question. I have one class which is abstract
    public abstract class Person
         private String firstName;
         private String lastName;
         private String title;
         private String dateOfBirth;
         private String homeAddress;
         private String phoneNumber;
         public static final String MR = "Mr";
         public static final String MISS = "Miss";
         public static final String MS = "Ms";
         public static final String MRS = "Mrs";
         public static final String DR = "DR";
         public static final String PROF = "Prof";
         public Person(String firstName, String lastName, String title, String dateOfBirth,
                         String homeAddress, String phoneNumber){
              this.firstName=firstName;
              this.lastName=lastName;
              this.title=title;
              this.dateOfBirth=dateOfBirth;
              this.homeAddress=homeAddress;
              this.phoneNumber=phoneNumber;
         And i have another class which extends this class
    public abstract class Borrower extends Person{
      public LibraryItem [] itemsBorrowed;
      private double currentFine;
      private int barCode;
      public LibraryItem [] getItemsBorrowed()
           return itemsBorrowed;
      public double getCurrentFine()
           return currentFine;
      public int getBarCode()
           return barCode;
      }When i try to compile these two classes, i get the error
    Cannot find symbal constructor Person(). The problem is that the tutor hates us providing default constructors, and i presume that this is what the error is asking for. Is there any way around this or does a default constructor need to be povided?
    cheers

    codingMonkey wrote:
    georgemc wrote:
    nick2price wrote:
    Ok, i get you, better call the superclass constructor as tutor hates me using no param constructorsChallenge him on that. Not only are they perfectly acceptable, they're a mandatory part of the JavaBeans spec.Personally, even though there are nothing wrong with them, I prefer to avoid no-arg constructors in a lot of cases. Usually when I feel that a class should always have certain attributes. I.e. instead of having a no-arg constructor for something like a Person class, I'd rather have a constructor that takes at least a name. It is true that the name could always be initialized in the no-arg constructor, but I would think that it makes more sense for a person to always have a name, rather than being called "null" or "N/A".If you plan on using any framework that uses the Beans spec (and while the inexperienced, self-professed "purist" might balk at that, you'll find it virtually impossible to avoid as a commercial coder) you won't be able to with those classes. Your argument about always needing a sensible starting point falls down where you have multiple disparate types that you are re-constructing. While it's quite nice to say "a Person should always have a Name", if you have, for example, a persistence framework that will generically map the results of various database queries back onto Java objects, you have to write some special case code for each class in your domain model, that says "in order to contruct this object, you first need to perform this query, then invoke this constructor with this part of the result of that query, then populate the rest of the properties using setter methods". For every class in your domain model. That's a fair amount of overhead. The no-args constructor model completely circumvents that, since everything's populated by the same generic code - beans introspection. Think about it. For every class in your model, you have to have separate chunks of code that are aware of - and hence, coupled to - a specific query, and a specific constructor of a specific class. Far from ideal.
    Even if you decide to roll your own code to manage peristence, configuration, remoting and the like, you'll still eventually settle on no-args constructors as extremely handy tools. Note that I'm all for the presence of other constructors as well, that do allow sensible creation of objects with certain values. Just that the no-args constructor is so infinitely useful for writing a huge amount of generic code
    I would think that it makes more sense for a person to always have a name, rather than being called "null" or "N/A".Me too. And there's nothing in any of my points that gainsays, or opposes that. You create a Person instance, and he's called "null" for a few clock cycles before you populate him from a database query - nothing wrong with that

Maybe you are looking for

  • My IPhone 5s has stopped sending e-mails suddenly.

    Yesterday afternoon my iPhone stopped sending my e-mails via aol. I can receive but not send. I have tried deleting and reinstalling the e-mail account, I have reviewed the sending server as suggested by some other support pages. I am at a lost as to

  • Frozen image with video out to HDMI

    I have my iMac connected via an HDMI adaptor through a 10' HDMI cable into a Hi Def TV. It was working well but suddenly froze with an image that happened to be a photo from iPhoto. That image remains whenever the cable is connected into the TV. When

  • Motion 5 is giving me a white outline around my luma matte.

    Hello,  I am having a small issue where my motion template is giving me a small white line around the edge of my luma matte. This project was created in Motion 4 and it looked fine and then I updated it to Motion 5 and now I get the white outline.  T

  • Creating a website and publishing it with trial version of DW CC (Was:'Dreamweaver CC 2014?')

    Hey guys i am taking an elective class in school named "Web Page Design", and we are using Dreamweaver. I first hated the class and now love it. The only reason i took the class is because my parents own there own business, and i want to surprise the

  • LMS 3.2 Config Editor : Config deployment is Not Attempted

    Hello gurus, Using config editor in LMS 3.2, I'm trying to deploy a config, that was previously saved to the "public configs", to a device (overwrite to startup-config). The job ends "Successfully", but looking at the detail, the deployment was "Not