Clonnig subclasses

Consider this class:
public MyClass{
  private int myint;
  private StringTokenizer mystr;
  public MyClass() {
  public Object clone(){
    try{
      Aux data = (MyClass) super.clone();
      return Aux;
    catch (CloneNotSupportedException e){
      return null;
}Now let's go to the old clonning problem...
When I use the clone method of the above object I get a new one (another instance) and it works for myint too.
But my problem is that StringTokenizer subclass. When I clone MyClass, in the new instance I got another reference to the same StringTokenizer object, ie. I'm stuck with 2 references of the same object.
How can I clone my ENTIRE class? With All other subclasses (in this case the StringTokenizer)?
I know that if I want to clone subclasses I have to write the clone method for them, but how can I do this for StrigTokenizer?
Thanks
Cassio

You might try extending StringTokenizer and keeping the parameters to the constuctor in local variables. Implement clone, and return a new CloneableStringTokenizer using those parameters (or copies of them if you want to go that far).

Similar Messages

  • How to check a single method is overriden in how many subclasses in ABAP.

    Hi Experts,
    I have a global superclass which had benn inherited by many other global subclasses. Is there any way to find out quickly (may be in a table ) in how many subclasses a particular method of the superclass is overriden?

    Hi Manuish,
    You can use the class CL_OO_CLASS to achieve the above, below is a sample code.
    DATA: lcl_oo_class TYPE REF TO cl_oo_class,
          lw_seoredef  TYPE seoredef.
    TRY.
        CREATE OBJECT lcl_oo_class
          EXPORTING
            clsname = 'Y_TEST_CHEN_CLASS_SUB1'.
      CATCH cx_class_not_existent .
    ENDTRY.
    WRITE: 'Class', '                              ', 'Refclass', '                         ', 'Over written method', /.
    LOOP AT lcl_oo_class->redefinitions INTO lw_seoredef.
      WRITE: lw_seoredef-clsname,'         ',
             lw_seoredef-refclsname,'         ',
             lw_seoredef-mtdname,'         ', /.
    ENDLOOP.
    Alternatively you can look up the table "SEOREDEF" directly.
    Regards,
    Chen
    Edited by: Chen K V on May 4, 2011 12:37 PM

  • Declaring top level classes instead of subclasses

    I seem to have misunderstood something very basic.
    It's always better, where possible, to declare the top-level class instead of the sub-class, right?
    Ok, then why do I have the following problem?
    I declare, from the JavaMail API the following:
    Message theMessage = new MimeMessage(session);instead of declaring directly the subclass like this:
    MimeMessage theMessage = new MimeMessage(session);but when I use a method which is only found in the MimeMessage class I get a compile error.
    [javac] 189.           theMessage.setSubject(subject, "iso8859_1");
    [javac] <-------------------------------->
    [javac] *** Error: No match was found for method "setSubject(java.lang.String, java.lang.String)".
    Have I really misunderstood something so basic?? Surely the compiler knows that theMessage is an instance of MimeMessage??
    Any clear explanation to explain why I get this compile error would be gratefully received. I have been faithfully declaring top-level classes instead of subclasses in my code, but if the compiler doesn't let you do so, then what's the point?

    Ok, my confusion was started by an article on the
    Collection classes which stated that:
    Map theMap = new HashMap(); was better
    programming practice.
    Yep.
    But the Map class is an Interface, right? - Whereas
    Message is a normal class with subclass MimeMessage.
    I think that's where my confusion started.Well, this isn't really a class vs. interface difference. It goes to which class (or interface) is the "highest" (closest to Object) and still has all the public interface you need.
    There are cases where you'll declare a variable to be of a base class type like Message.
    You just need to get into the habit of separating the left side of the = from the right side. On the left, you put the bare minimum that completely meets your needs. You say, "I need a List" or "I need a Map" or "I need a SortedMap" (a subinterface of Map) or "I need a Message" or "I need a MimeMesage".
    Then, on the RHS =, you decide which particular class best implements the public interface that you said you need (by declaring it on the LHS). "For my Map, I'll use a HashMap." "For my Message, I'll use a MimeMessage." "For my MimeMessage, I'll use a MimeMessage".

  • How do I close a JInternalFrame when using subclasses and a separate cla...

    The heading should be: How do I close a JInternalFrame when using subclasses and a separate class for the actionListener?
    I have just created a JInternalFrame appclication and now I want to structure up my code. I have a Superclass that contains the usual settings for the two JInternalFrame:s, and the two subclasses with frame specific information. Both the JInternalFrames use the same OK button. I want to have the actionListener outside the classes to avoid repetition of code. But the dispose()-function does not work properly, it does not close the opened JInternalFrame. What�s wrong?
    class Superclass extends JFrame
         JButton b= new JButton("ok");    
         Superclass()
    class Subclass1 extends Superclass
         Subclass1 ()
              add(ok);
           ok.addActionListener(new Listener());
    class Subclass2 extends Superclass
         Subclass2 ()
              add(ok);
           ok.addActionListener(new Listener());
    class Listener extends Superclass implements ActionListener
         public void actionPerformed(ActionEvent e)
                   dispose();
    }How do I controll in the Listener class that the button in Subclass1 is beeing pressed?

    First of all I think I misunderstood your question. You said you had two internal frames, so I thought you wanted to close the internal frame.
    It now looks to me like you want to close the entire JFrame, which makes the code even a little easier. Something like:
    JComponent component = (JComponent)event.getSource();
    JFrame frame = (JFrame)SwingUtilities.windowForComponent( component );
    frame.dispose();
    Ok, I will make a try:
    public static Container getAncestorOfClass(Class c, Component comp)
    w.getAncestorOfClass(w, this); Fiirst you need to learn the basics of reading the API.
    "getAncestorOfClass()" is a static method. That means you don't use a variable to invoke the method. You use the class itself.
    "w" is a variable, which is a JFrame, but that is not what the first parameter should be. The first parameter is a "Class".
    "this" will refer to your Listener class, but you need the Component that generated the ActionEvent.
    When I thought you wanted to close an internal frame then the code would have been something like:
    JComponent component = (JComponent)event.getSource();
    Container container = SwingUtilities.getAncesterOfClass( JInternalFrame.class, component );
    JInternalFrame internalFrame = (JInternalFrame)container;
    internalFrame.invokeSomeMethodHere();If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)", that demonstrates the incorrect behaviour.
    http://homepage1.nifty.com/algafield/sscce.html

  • Inheritance, class indicator field and subclasses

    Hi
    Ok, I have an inheritance model with a base class (let's call it BaseClass), which is abstract. Every subclasse of BaseClass have a different implementation, but no additional attribute. I don't want to map all subclasses in Mapping Workbench, so I mapped BaseClass and configured inheritance to use a field as a class indicator (using the java class name).
    Now, to read all subclasses in one single query, I do this:
    Collection result = session.readAllObjects(BaseClass.class);
    Now the problem is that TopLink generates the following SQL:
    SELECT JAVA_CLASS_NAME, [...] FROM BASE_CLASS_TABLE WHERE JAVA_CLASS_NAME = 'com.[...].BaseClass'
    Well, obviously this is not what I expected, since this will not return anything! I tried to use the "Read Subclasses on Query' option, to no avail. Am I missing something here? I thought this would pretty staight forward... :-(
    TIA
    Regards
    Eric Morin

    You must always map all subclasses that you wish to persist/read. If TopLink does not have a descriptor for a class it will persist/instantiate it as its superclass descriptor class.
    If you explictly configured your descriptor to read subclasses on queries in code (descriptor.getInheritancePolicy().readSubclassesOnQueries()) it would generate the correct SQL that you want, however it would return you all instances of the root class, not the subclasses. The only way to read subclasses is to map them.
    If you don't want to have to map all of the classes in the Mapping Workbench, you could just add the descriptor's for the subclasses in code.
    i.e.
    List allSublcasses = getAllMySubclasses();
    for (Iterator iterator = allSublcasses.iterator(); iterator.hasNext(); ) {
    Descriptor descriptor = new Descriptor();
    Class subclass = (Class) iterator.next();
    descriptor.setJavaClass(subclass);
    descriptor.getInheritancePolicy().setParentClass(subclass.getSuperClass());

  • Using RTTI to identify subclasses

    Hello, here is my dilemma:
    Class B inherits from Class A.  Classes C and D inherit from Class B.
    I need to test if object O is an instance of Class A or any of its subclasses (ie Class A, B, C or D).  Using the method GET_RELATIVE_NAME is not suitable because then I must know the actual name of the subclass, which I will not.  The methods APPLIES_TO and APPLIES_TO_CLASS do not seem to account for inheritance (ie Class D APPLIES_TO Class A is false, even though Class A is a superclass of Class D).
    Any feedback would be very nice.  I'd like to accomplish this, if possible, using RTTI since it is more elegant than simply casting the object into a reference of type Class A and seeing if an error is thrown.
    I'm on 4.7, WebAS 6.30.
    Cheers,
    Mike

    I know this is NOT a RTTI way of doing this task and I can tell you from looking for hours at RTTI that it does not look at the information in this "bottom-up" manner.  Although, this would be totally unsupported you can recursivley read the VSEOEXTEND table.  That table keeps the relations of all classes and sub-classes.  Sadly, CL_ABAP_CLASSDESCR is marked as final so you can't even subclass it to add this functionality.
    hope this helps.
    -d

  • Know Java classes & subclasses

    I´m wirking with Forms & Report 10GR2.
    I´m working with Forms & Report from year 1.997. Normallly I rotate between 8 or 9 diferents application. My applications now appear a little old fashioned. Looking for to resolve this I find a article from Grant Ronald, I think well know in this forum, He have resolved me some question that I post here. In this article Grant say this :
    Extending the Forms UI
    So how can you achieve the balance of giving your
    Forms application the makeover to bring it into the 21st
    century without having to embark on a massive program
    of redevelopment or user retraining?
    The answer lies in the architecture of Oracle Forms.
    For a Forms application running through a browser, the
    user interface is rendered as a Java applet. This Java applet
    includes a number of Java classes responsible for
    rendering each of the Forms’ UI components. The magic
    lies in the fact that since each UI component is, in effect,
    a Java class, it can be subclassed. This means you can
    create your own component that does everything the
    base component does, but with your own added code to alter
    the functionality or look and feel.
    Really a piece of gold, in this, he give you the key to can change the forms look & feel.
    But, now come the questions, how I can do this? how I know what classes use forms for display a buttom for example, what I must do for subclasses it?
    is there any example or documentation that can help me? if yes ¿where? Can any of the gurus give me some links to explore this?
    Thanks & regards everybody.

    Look at this.
    http://fdtool.free.fr/LAF/doc/Oracle_Forms_Look_and_Feel_project.htm
    It is not supported by Oracle, but is widely used. All support for its use will come from its web page.

  • How to get the class name of all available subclasses

    Hi there!
    Im developing an eComerce site as part of my studies this semester using JSP and mySQL. It's part of a bigger management system for a fictional company.
    In the user interface, when adding new products to be available for sale on the website, I want the administrator to be able to choose what kind of product is being added. In the database I have the superclass[i] products with subclasses[i] harddrives, monitors etc.. The question is, can I somehow get the names of the subclasses constrained to a certain superclass? Maybe this question is more related to SQL querys than to JSP, but any help is appreciated:-)

    First of all it is not conventional (or at least I find it very confusing) to call things as super class or sub class when referring to them in the database.
    Why? because super class and sub class are really concepts in Object Oriented Programming languages, and probably (not sure) in Object Oriented Databases.
    So I would call them main categories of products and sub categories of products.
    And in databases I assume you have tables?
    So say the table with main categories would have a primary key and a text field. The primary key is just like an index, and the text field holds the Main Category.
    Similarly you would have another table representing sub categories.
    But how would you associate a set of sub categories to each main category?
    For this you would need a Foreign Key in the sub categories table.
    The foreign key of a sub category maps to the primary key of the main category. Get it? If not you'll need to learn relational databases.
    So if you know SQL you could write a SELECT statement in MySQL as follows:
    SELECT product_category_name FROM product_sub_category psc, product_main_category psm WHERE psc.product_main_category = psm.product_main_category AND psm.product_main_category = 'Whatever Cagegory Name';
    Message was edited by:
    appy77

  • Where to put methods in a abstract base class - subclasses system

    Hi,
    I’d like to ask a question on some basic design practice.
    When there are methods which are common in some subclasses so I would like to “move them up” in the base abstract class, I would also like to make sure that the ADT concept of the base class itself is not broken. So I don’t want to have methods in the base class that are not general enough to be there. How to resolve this?
    For example I create a base abstract class Vehicle. Then I create subclasses Plane and Tanker and realize that the startEnginge() method in them is the same and in order remove the duplicated code, I can put it in Vehicle. But later there may be Bicycle or Sled subclasses which don’t need startEngine().
    In a broader sense, I would like to keep the Vehicle class as similar to the real word concept of vehicles as possible. And not evey vehicle have engine of course.
    What is the solution?
    Extending the class hierarchy by injecting another abstract class between the base and the subclasses? (e.g: VehicleWithEngine)
    I suppose I can’t use Interfaces because I need to have the common implemenations as well.
    Thanks for any comments in advance,
    lemonboston
    ps: I am a beginner and don't know the terminology, so if there are programming expression for the followings for example, I would be thankful if someone could help with this too:
    - moving common methods up in the class hierarchy
    - injecting a class in the hierarchy
    - abstract base class - subclasses system

    lemonboston wrote:
    Hi,
    I’d like to ask a question on some basic design practice.
    When there are methods which are common in some subclasses so I would like to “move them up” in the base abstract class, I would also like to make sure that the ADT concept of the base class itself is not broken. So I don’t want to have methods in the base class that are not general enough to be there. How to resolve this?
    You are talking about code.
    Instead you need to talk about the design.
    The base class represents conceptually a 'type' of something. That 'type' defines behavior. That behavior is what goes in the base class nothing else (in terms of design.)
    If you have common functionality which does not fit into the definition (design) of the 'type' then you put it in another class and use (composition) that class in the sub class.
    For example I create a base abstract class Vehicle. Then I create subclasses Plane and Tanker and realize that the startEnginge() method in them is the same and in order remove the duplicated code, I can put it in Vehicle. But later there may be Bicycle or Sled subclasses which don’t need startEngine(). No that is not how it works.
    You have specific examples of some vehicles and then you need to manage those types generically. That is the first step.
    Second step is then to determine what the exact 'type' is that you want to manage. And you use the requirements of the need to create the 'type'.
    Then you look at the specific examples to determine how they will meet the needs of the type.
    Thus if I have an application that must start the engines of all the vehicles in the city then I must have a vehicle class which has startEngine.
    But if I have an application that manages vehicles as inventory (like a retail store) and then decide that because my examples both have engines that I might as well move it into the base class. In that case there is no 'need' for the application to manage starting vehicles. The fact that both have engines is irrelevant.
    So looking back at your example you have stated functionality about your specific types but you have not stated anything about why your application needs to deal with that functionality generically.
    Another way to think about it is that you do not put the shared functionality in the base because you can but rather because you must.

  • Best way to update subclasses of UILabel and UIImageView?

    Hello- I'm looking for some strategic suggestions before I dive into this.
    I have subclassed UILabel and UIImageView to get text and tint colors from a theme color stored in UserDefaults and it all works fine, but I'd like to reduce the code footprint a bit more if I can.
    Currently, I am overriding -initWithFrame in the ImageView and -drawTextInRect in the Label so that on initial appearance each instance grabs the theme color automatically.
    However, if I switch the theme color and come back to the view, I have to put a line of code in the view controller to tell each Label and Image to update to the proper color, because they've already been drawn. Calling -setNeedsDisplay of their parent view does not do the trick, and there is no -viewWillAppear method to override in the super classes....
    I guess what I need to do is set up a notification I can broadcast to the two subclasses, but I am not sure if this is the most economical approach, or exactly how to go about it.
    Basically anything that gets me away from having to manipulate each instance of the subclass every time the color is updated would be fantastic.
    Any ideas?

    My environment is very sensitive to disruption (including popups), so I took the least disruptive route I could find. My solution leverages the
    STATIC=1 install switch (see:
    http://www.oracle.com/technetwork/java/javase/silent-136552.html). This forces a unique install directory based on the version you are installing.
    Example:
    C:\Program Files (x86)\Java\jre1.6.0_45
    C:\Program Files (x86)\Java\jre1.6.0_51
    C:\Program Files (x86)\Java\jre1.6.0_60
    In the upgrade scenario it leaves the existing version alone and installs the update side-by-side. Next time the user relaunches their JAVA application it leverages the latest installed version.
    When I create the update in SCUP the install argument looks like this: /s STATIC=1 IEXPLORER=1 MOZILLA=1
    Following our regularly scheduled reboot window, I create a collection that has computers with both old and new versions installed. I then send out a silent uninstall for the outdated version, which in most cases is no longer in use, and therefore leaves
    the user unaware that there was a change.

  • Static block in superclass to initialize static members in subclasses

    I am trying to create several classes that are all very similar and should derive from a super class because they all have common members and are all initialized the same way. I would prefer every member of my subclasses to be static and final as they will be initialized once and only once. I can not figure out the best way to make this work. Here is an example (using code that does not work, but you can see what I am trying to do):
    class Super
        protected static final String initializedInEachSubclass;
        protected static final String alsoInitializedInEachSubclass;
        // these need to be accessed from anywhere
        public static final String initializedInSuperclass;
        public static final String alsoInitializedInSuperclass;
        // this static initialization block is exactly the same for every instance
        static
            // initialize these based on what the subclasses initialized
            initializedInSuperclass = initializedInEachSubclass + alsoInitializedInEachSubclass;
        private Super () {} // never instantiated
        public static final String getMoreInfo ()
            // the same for each instance
            return Integer.toString (initializedInEachSubclass.length ());
    class Sub1 extends Super
        static
            initializedInEachSubclass = "My String for Sub1";
            alsoInitializedInEachSubclass = "My Other String for Sub1";
        private Sub1 () {} // never instantiated
    }The problem with the above code is that the static block in Super uses static final variables that have not been initialized yet. I can't make Super abstract. If I initialize the final variables in Super, then I can not reinitialize them in Sub1. But if they are not final, then they could be changed after being initialized (which I would rather not allow). I could make everything protected and not final and then make public get... () methods, but I like accessing them as attributes. It seems like this should be possible, but everything I have tried has led me to a catch-22.
    Any ideas on how I can put all my redundant initialization code in one place but still allow the subclasses to initialize the static members that make each of them unique? I will be happy to clarify my examples if you need more information.
    Edited by: sawatdee on Jan 3, 2008 9:04 AM

    sawatdee wrote:
    I am basically trying to avoid having redundant code in several classes when the code will be exactly the same in all of them.That's the wrong reason to subclass. You subclass to express type specialization. That is, a Dog IS-A Mammal, but it's a special type of Mammal that implements certain common mammal behaviors in a dog-specific way. A LinkedList IS-A List, but in implements common list operations in linked-list-specific ways.
    I don't really need to have the static final members in a superclass (and I don't even need a superclass at all), but I don't know how else to execute a big static initialization block in several classes when that code is exactly the same in all of them. Without knowing more details about what you're trying to do, this sounds like a case for composition rather than inheritance. What's now your superclass would be a separate class that all your "sublasses" have a reference to. If they each need their own values for its attributes, they'd each have their own instances, and the stuff that's static in the current superclass would be non-static in the "subs". If the values for the common attributes are class-wide across the "subs", the contained former super can be static.
    public class CommonAttrs {
      private final String attr1;
      private final int attr2;
      public CommonAttrs(String attr1, int attr2) {
        this.attr1 = attr1;
        this.attr2 = attr2;
    public class FormerSub1 {
      private static final CommonAttrs = new CommonAttrs("abc", 123);
    ... etc. ..

  • [svn:osmf:] 15256: Add metadata to the resource of elements created by LoadFromDocumentElement subclasses indicating the derived resource .

    Revision: 15256
    Revision: 15256
    Author:   [email protected]
    Date:     2010-04-07 09:51:55 -0700 (Wed, 07 Apr 2010)
    Log Message:
    Add metadata to the resource of elements created by LoadFromDocumentElement subclasses indicating the derived resource.  This allow recipients of MediaFactoryEvent.MEDIA_ELEMENT_CREATE to be able to determine where a created element derives from.  Updated F4M code and SMIL code, plus unit tests.  Also added MediaType to resources generated by SMILMediaGenerator, in case they lack file extensions.
    Modified Paths:
        osmf/trunk/framework/OSMF/org/osmf/elements/f4mClasses/ManifestParser.as
        osmf/trunk/framework/OSMF/org/osmf/metadata/MetadataNamespaces.as
        osmf/trunk/framework/OSMFTest/org/osmf/elements/f4mClasses/TestManifestParser.as
        osmf/trunk/plugins/SMILPlugin/org/osmf/smil/loader/SMILLoader.as
        osmf/trunk/plugins/SMILPlugin/org/osmf/smil/media/SMILMediaGenerator.as
        osmf/trunk/plugins/SMILPluginIntegrationTest/src/org/osmf/test/smil/loader/TestSMILLoader .as

    Yes, it seems to be a kernel bug. Previously, my wife used Windows for years and nothing like this happened. Now, she tells a lot about Linux systems :-)
    An example of this very-ugly-workaround for somebody who'll find this topic struggling with the same problem:
    $ cat /etc/pm/sleep.d/99_fix_time_shift
    #!/bin/bash
    # fixing https://bbs.archlinux.org/viewtopic.php?id=173487
    case "$1" in
    suspend)
    date +%s > /tmp/suspend.log
    resume)
    was=`cat /tmp/suspend.log`
    now=`date +%s`
    # time shifts for 68 hours
    if [ $now -gt `expr $was + 244800` ]; then
    date -s "`date -R --date="-68 hours ago"`"
    ## sleep 30; ntpdate ntp.ubuntu.com
    fi
    esac
    Last edited by shurup (2014-03-26 16:25:55)

  • A plea for a readable Java (for each, Set Integer & subclasses )

    I like the new language features a lot, but I don't like the proposed syntax. I thought the great thing about Java was that it got us away from the awful C++ punctuation soup. Here's my proposal for a more readable syntax without adding new keywords to the language:
    for each (Item i in collection) { ... }
    'for' is already a keyword. By separating this, we can part this production as:
    ForStatement: for Identifier ( Type VariableDeclaratorId Identifier Expression ) Statement
    (Using the productions and terminals in the JLS).
    Note that, after the first 'for' is encountered, the parser can look at the next token (right-paren or Identifier) to determine whether this is a 'for each' or an old-style 'for' statement. We don't need to make 'each' or 'in' into an keyword, and they don't conflict with variable, method, or class names. Semantic checking will simply ensure that the Identifiers mentioned have the appropriate contents.
    Next, for the variance syntax:
    Set<Integer & subclasses> Set<Integer & superclasses> Set<*>
    Again, the grammar here is:
    Identifier < Type & Identifier> | Identifier < * >
    The '&' is not otherwise allowed in parameterized types before 'extends', so there is no grammar ambiguity. The Identifier following & in this production is checked to be only 'subclasses' or 'superclasses' (otherwise a syntax error). There is no conflict with class names, because Set<Integer & Foo> is not a legal use for a class named 'Foo'.
    To save typing, perhaps 'subclasses'/'superclasses' can be shortened to 'sub'/'super' without sacrificing readability. I expect invariant types will still be most-heavily used, so I don't think fingers will be hurting all that much.
    Perhaps this Identifier-not-keyword idea can be taken further with some of the other new grammar productions? I await suggestions!
    Comments/Votes?

    Read the papers on variance. In a nutshell, a generic
    type A<X> is not related to the generic type A<Y>,
    regardless of the relationship between X and Y.
    Variance changes that and is a proposed addition in
    the (very) new generics implementation.I find your comment confusing. Maybe I am misunderstanding the OPs intentions with this syntax.
    Right now:
    List<java.util.Date> is a List that only allows instances of java.util.Date. I can still add a java.sql.Date to this list, though, because an instance java.sql.Date is an instance of java.util.Date.
    His proposal:
    List<String & superclasses> Now given the current syntax, I would take this to mean that this defines a List that takes instances of String and an instances of any superclass of String i.e. instances of Object i.e. anything other than primitives.
    I think what you are saying is that if I define a method (for example) like so, method(List<java.util.Date>) that I can't pass an List<java.sql.Date> to it. Understood, though I find that puzzling because that means an method that accepts a List shouldn't accept a List<String>. I didn't see anything in the OPs post that makes me think that is the context which this syntax would be used though it could be. Clarification would be nice.
    In that context, however, List<String & superclasses> would still be quite useless because wouldn't it still evaluate to a method that accepts a List<Object>? What would be the value of rejecting more specifc List types but allow the most generic List type?

  • Classes and subclasses given as String input - question

    Hello, I am new in Java so please don't laugh at my question!!
    I have a method as the following and I am trying to store objects of the type Turtle in a vector. However the objects can also be of Turtle subclasses: ContinuousTurtle, WrappingTurtle and ReflectingTurtle. The exact class is determined by the String cls which is input by the user.
    My question is, how can I use cls in a form that I don't have to use if-else statements for all 4 cases? (Imagine if I had 30 subclasses).
    I have tried these two and similar methods so far but they return an error and Eclipse is not of much help in this case.
    Simplified methods:
    //pre:  cls matches exactly the name of a valid Turtle class/subclass
    //post: returns vector with a new turtle of type cls added to the end
    private Vector<Turtle> newturtle(Vector<Turtle> storage, String cls){
         Turtle t = new cls(...);
         storage.add(t);
         etc.
    private Vector<Turtle> newturtle(Vector<Turtle> storage, String cls){
         Turtle t = new Turtle<cls>(...);
         storage.add(t);
         etc.
    }Thanks for your help.
    p.s.: I didn't know whether to post this question here or under Generics.

    a Factory is atually very simple (100x simpler than reflection).
    example:
    class TurtleFactory
      public Turtle makeTurtle(String typeOfTurtle)
        if (typeOfTurtle.equals("lazy") { return new LazyTurtle(); }
        else if (typeOfTurtle.equals("fast") { return new FastTurtle(); }
        <etc>
    }While at first this doesn't look any better than your original problem, what we've done is made a class that is responsible for all the types of turtles. This will also benefit in case some turtles need initialization or need something passed to their constructor. You encapsulate all that knowledge in one place so you rcode doesn't become littered with it else ladders.

  • Is it possible to make a local class accessible in SE24 subclasses?

    G'Day,
    The scenario is simple: I have a global class created in SE24 with a local helper class defined in the local definitions/implementations sections. The issue is anything declared here is private; however I would like my local class to be available in the subclasses of the global class as well. In other words I want a protected local class.
    ZCL_SUPER  --> contains local utility class LCL_HELPER
        |
        V
    ZCL_SUB    --> needs to make use of LCL_HELPER's methods.
    I've messed about with different definitions and FRIENDS but no joy.
    I can think of two alternatives:
    1. Write a protected wrapper method in zcl_super to expose each lcl_helper method to the subclasses. Annoying, cumbersome, defeats the object of using a local class in first place.
    2. Define LCL_HELPER in an include which is added to all subclasses. This effectively makes it public as I no longer control where LCL_HELPER is used. (Unless I do funky stuff with packages which we don't do on this project).
    Any better suggestions/ideas/workarounds?
    Cheers,
    Mike

    Hi Naimesh,
    Thanks for the input. Interesting idea about interfaces, I need to play around with this a little.
    I don't agree what I'm trying to do would violate encapsulation. I'm after the same visibility level as other class component type. i.e. methods can be private, protected or public. Classes can be local or global - a protected class visible to subclasses would fit the principles quite well.
    Consider a global class GADGET which has a protected attribute WIDGET, type ref to a local class. The widget's methods and attributes should really be separate because it is it's own entity, but at the same time it has no business in the wider SAP system. ==> Perfectly sensible use of a local class.
    Now, this widget can turn, open, close, light up. So in a GADGET method I can say WIDGET->TURN( ). Create a subclass of GADGET and boom, all such code working with WIDGETs is broken. In some ways it makes local classes a little un-future-proof.
    The bothersome thing about the workarounds is that they de-object-orient the two objects by forcing us to create protected methods TURN_WIDGET LIGHT_WIDGET OPEN_WIDGET etc. on the GADGET class. Which goes back to my original point that there's little benefit of creating a local class if we need to do this....
    Or am I missing something?
    Cheers,
    Mike

Maybe you are looking for

  • How to use used backed up itunes on new computer?

    I've been searching and searching and I can't find a specific answer to what I need to do.  This is what I want to do.  I have a Macbook pro and I want to create a new itunes library for my husband to use for his library.  Easy enough, I found instru

  • How do I have a totalizer reset at the end of every month?

    We are using Lookout 5.1 in an application that is receiving a Modbus input giving us a totalizer value.  We need to have this value reset to zero at the end of every month.  Also want the monthly total to be sent to an excell spread sheet.  All help

  • Save file to desktop, not load in browser window.

    Hello,     I've created a page where I describe certian videos or audio files and then give the visitor the option to download that video or audio clip. These clips are saved as .mov and .wav . My issue is that I set up a link to those files. When th

  • How to override a method in an inner class of the super class

    I have a rather horribly written class, which I need to adapt. I could simply do this if I could override a method in one of it's inner classes. My plan then was to extend the original class, and override the method in question. But here I am struggl

  • The FLOW isn't parallel - why?

    The BPEL process starts out with three parallel flows. Each flow makes (1) a database access, (2) Using aswitch determines it is appropriate to proceed, (3) Invokes a Asynchronous process, (4) Receives the result of the process, then all three flows