Polymorphism and casting

Hi there, I would be grateful if I could get some help on the following:
I am writing an application that dynamically processes diferent shapes (e.g. line, circle, rectangle) using a number of algorithms (algorithmA, algorithmB, algorithmC etc).
Therefore, I have defined an abstract superclass called Shape and the subclasses Line, Circle, and Rectangle. I have also difined an abstract superclass called ShapeProcessor and a number of subclasses, ShapeProcessorA, ShapeProcessorB, ShapeProcessorC... Each shapeProcesssor class has overloaded member methods (called processShape) to process each shape type. So my ShapeProcessor class looks like:
public abstract class ShapeProcessor{
     public abstract void processShape(Line aLine);
     public abstract void processShape(Circle aCircle);
     public abstract void processShape(Rectangle aRectangle);
For instance, if I want to process a cirlce using the algorithm B I can write something like:
ShapeProcessor aShapeProcessor= new ShapeProcessorB();
aShapeProcessor.processShape(new Circle());
My problem is when I have an array of Shape objects which I need to process. Before I can pass each shape to the processShape method I need to cast it first (i.e. to convert them from the abstract superclass Shape into a particular shape, Circle, Rectangle etc).
A crude way of doing that it will be to retrieve the "Class" of each shape and use a switch statement to cast each shape. However, this is not what Object-Orientation is all about. Is there any better approach?
best regards,
Kyri.

If you make the superclass method definition abstract,
then once again you get the benefit of compile-time
checking, no matter how many classes you add.I'm not sure I understand what you mean by this.
Let's take mattbunch's approach, where a ProcessableShape calls a method in ShapeProcessor. If I understand what you're saying, you would have that method be abstract. We could also define ShapeProcessor as an interface, like so:
    public interface ShapeProcessor
        void processShape(Line shape);
        void processShape(Circle shape);
        void processShape(Ellipse shape);
    }OK, here we have our "case" statement, represented by separate methods in the interface. The ProcessableShape subclass calls processShape, passing itself as the argument, and the compiler picks the appropriate method. Each implementation of ShapeProcessor needs to implement all the methods for defined by the interface.
The problem comes when you change the definition of ShapeProcessor but don't recompile all your implementations. This is pretty easy to do with javac, because there isn't necessarily a direct dependency. You can of course overcome the problem with a rigorous build process.
However, if your builds do get out of sync, your app is going to blow up. Perhaps not right away, perhaps not until you happen to process the unsupported shape. But because Java does dynamic, as-needed binding, the possibility will be there.
This isn't a Java-specific problem. I suspect that it would happen with DLLs, and know that it happens with UNIX shared libraries. The key to avoiding it is to eliminate unnecessary interdependencies, especially (in my experience) between work and worker objects.
And, to head off the obvious critique: yes, there are times that you can't avoid such dependencies. I suspect the OP's original design was one of those times. But if by changing the design slightly, the dependencies could be eliminated, you have a better design.

Similar Messages

  • Polymorphism and Up-Casting diff???

    Plz tell me the diff between
    Polymorphism and Up-Casting
    i m so much confuse

    absctract class A
    method1();
    class B extends A
    method1( ){ }// overrides, polymorphic method
    method2( ) {}// non-polymorphic method
    class C extends A
    method1( ){ }// overrides, polymorphic method
    method3( ) {}// non-polymorphic method
    class Test
    public static void main(String[] args )
    A a = new B();
    // only polymorphic method can be called
    a.method1();// called from B class
    // we can't call a.method2(); b/c its a non-polymorphic, for that we need full control to use casting
    B b = (B)a;
    b.method2();
    I agree with schapel's point of view.
    Taqi

  • Polymorphism and JSF

    I was wondering if anyone can take a look at my blog entry about polymorphism and JSF.
    http://www.evolutionnext.com/blog/2005/03/07/1110236621000.html
    I would like to see what input any of you may have.

    absctract class A
    method1();
    class B extends A
    method1( ){ }// overrides, polymorphic method
    method2( ) {}// non-polymorphic method
    class C extends A
    method1( ){ }// overrides, polymorphic method
    method3( ) {}// non-polymorphic method
    class Test
    public static void main(String[] args )
    A a = new B();
    // only polymorphic method can be called
    a.method1();// called from B class
    // we can't call a.method2(); b/c its a non-polymorphic, for that we need full control to use casting
    B b = (B)a;
    b.method2();
    I agree with schapel's point of view.
    Taqi

  • Get values from a node and Cast it back to a table

    Hi guys!
    Anyway know if it is possible to get the values from a table(That was binded previously) and cast it back to a table structure so i can manupilate the fields inside...
    My scenario here is to get an input and mass update tis input into the corresponding field in the table...
    Any suggestions are welcome and points will be awarded generously! ")

    Hi Ravikiran,
    In your example you update node node_list with the content of internal table tab_list..
    The content of the node can be retrieved as an itab using:
      tab_list = node_list->get_static_attributes_table( ).
    This method only returns the values static attributes of the node. Dynamic attributes added at runtime using dynamic programming are not returned, since they are managed in a different inside of the context node.
    Best regards,
    Thomas

  • Get runtime class and cast object to it?

    Hi,
    public interface Msg
    Msg msg=msgLib.get(msgType);
    Msg msg2=msg.clone(); //problem! cannot find clone in  x.y.Msg!
    ...Shouldn't msg be resolved to the implementing class (MsgReply for example) and use the "clone()" method, that i have declared in that class -which overrides the one of Object class?
    If no, is there a way to find the runtime class -probably use "getClass"- and cast to it? How?
    Thanks

    There are many implementing classes; i want to get the runtime class. Something like:
    (msg.getClass())msg.clone();
    Message was edited by:
    uig

  • Method chaining and casting

    I was wondering if anyone knows whether it is possible to somehow apply method chaining on an object that requires a cast.
    For example:
    ArrayList ar = new ArrayList();
    ar.add(new Integer(3));
    int i = ar.get(0).intValue();The third line obviously produces a compile error to the effect that you can't call method intValue() on object Object.
    To get the int value from the ArrayList above I have to do the following:
    ArrayList ar = new ArrayList();
    ar.add(new Integer(3));
    Integer intObject = (Integer)ar.get(0);
    int i = intObject.intValue();Is it at all possible to get the int value somehow without explicitly creating an Integer object? Is there a possible way to combine method chaining and casting in this case?

    You may combine the two lines by casting at the same time:
    int i = ((Integer)ar.get(0)).intValue();
    Notice the additional brackets to help the compiler understand the precedence of your intentions. It makes no sense if the compile tries to call intValue THEN cast to Integer.
    When you call:
    Integer intObject = (Integer)ar.get(0);
    No Integer object is created, only a reference to the object is created. I'm not sure if an implicit reference is created in the previous example, but I see no substantial benefit using the first method. In fact I won't use it as its not very readable (to me).

  • What is Polymorphism and how is it being applied?

    Dear All
    I need to seek your help in finding out what is polymorphism and how is it being applied?
    Thank you.

    Thank You So Much For This Link!
    http://faculty.frostburg.edu/cosc/htracy/cosc390/LM7Polymorphism/PolymJava.html
    I Am FOREVER GRATEFUL!
    See Ya Later - I got some Homework To do!!!!!!!!!!
    Jason
    REALLY ITS GREAT AND EXACTLY WHAT I'M LOOKING FOR TO LEARN JAVA
    Anybody that's really wants to learn this stuff from home should check this out. A little hard to follow the format, but definately readable.
    Edited by: jasonwpalmer on Nov 4, 2007 1:42 PM

  • I need clarification regarding REFERENCE TYPES and CASTING.

    Hello all,
    I'm taking a course on the fundamental of JAVA. Everything's been going smoothly until I slammed into the the concept of CASTING and REFERENCE TYPES. Flat--out == I DON'T GET IT?
    I'm having trouble with...
    CONVERTING REFERENCE TYPES
    CASTING BETWEEN REFERENCE TYPES
    WORKING WITH REFERENCE TYPES
    I understand what's happening from an academic vantage point. I just don't understand why you'd want to convert REFERENCE TYPES? What would be an application of such an exercise?
    1. What IS a REFERENCE TYPE -- exactly?
    a. what are we referencing?
    b. type? type of what??
    for example... why would you want to do a widening conversion, a conversion of the hierarchy tree?
    I understand the concept of OBJECTS, CLASSES, METHODS and CONSTRUCTORS so far...
    I think it's the terminology that's screwing my up.
    Thanks,
    Alex

    ok... wow, thanks J.
    So--in a nutshell-- we're making it so that different
    objects:
    ie,. ford(), chevy(), honda(), lotus() and
    dealers()... so and so forth()...
    all share the resources(for lack of a better word) of
    the Auto Class? because all of those auto brand
    objects and one redically different object can be
    unrelated, correct?Um, yes and no.
    I just ran with the example you had, but that probably included too many concepts and they got muddied up.
    Yes, Chevy, Ford etc. all share the characteristics of Auto, since they're all subclasses. But that's just inheritance, and has nothing to do with casting.
    A "reference type" can loosely be described as a variable that refers to an object. (Constrasted with "primitive types" which are int, char, float, etc. and don't refer to objects--they just hold values.)
    Casting just tells the compiler that even though as far as it knows you only have a reference to some superclass, the object that reference points to will in fact be an instance of a subclass, and so treat it as such (e.g., we can now call methods that the subclass has that the superclass lacks).
    (You can also cast primitives, but one thing at a time.)
    So let's say you have class A (which extends object) and B extends A.
    A a = new B();
    B b = a; // won't compile. compiler sees the "A a" on the left of the =, not "new B()" on the right.
    B b = (B)a; // works because we're telling the compiler, "Dude, I'm seriously. This is a B.
    Note that if we had done new A() instead of new B(), it would still compile--the compiler would trust us. But at runtime, we'd get a ClassCastException, since we wouldn't actually have a B object.
    /**folks, I'm a web designer that has to learn Java
    so that I can perform my duties as a JSP author here
    at work. I tried to learn JSP sans Java and that was
    a simple exercise in ignorance.-- it's really hard
    without understanding the root concepts of Java and
    for that matter, C. Concepts like "polymorphism,
    inheritance, object references... are completely
    foreign to me. **/It's a rather big leap from web designing to OO concepts. Take your time, and don't be discouraged if you feel completely confused. It's a prerequisite. :-)

  • Trouble with primitive arrays and casting, lesson 521

    hi everyone!
    there is a problem i discovered right now - after years with java where was no necessity to do this.....
    and i'm shure this must have been the topic already, but i couldn't find any helpful resource :-/
    right here we go:
    1. an array is a (special) kind of object.
    2. there are "primitive" arrays and such containing references to objects. of course - and i imagine why - they are treated differently by the VM.
    3. then both are - somehow - subclasses of Object. whereas primitive types are not really, primitive-arrays are. this is hidden to the programmer....
    4. any array can be "pointed" at via local Object variable, like this:
    Object xyz = new int[6];
    5. arrays of Objects (with different dimensions) can be casted, like this:
      Object pointer = null;
      Object[]   o  = new SomeClass[42] ;
      Object[][] oo = new OtherClass[23] [2] ;
      Object[][][] ooo = new OtherClass[23] [2] [9] ;
      o = oo = ooo;     // this is save to do,
                                   //because "n-dimensional" object-arrays
                                  // are just arrays of  other arrays, down to simple array
    pointer = o;         // ok, we are referencing o via Object "pointer"6. but, you cannot do this with primitive types:
      int[]  i1 = new int [99] ;
      int[][] i2 = new int [1] [3] ;
      i1 = i2                  // terror: impossible. this is awful, if you ask me.
                                   // ok, one could talk about "special cases" and
                                   // "the way the VM works", but this is not of interest to me as
                                   // a programmer. i'm not happy with that array-mess!
      pointer = i2;       // now this is completely legal. i2, i1 etc is an object!7. after the preparation, let's get into my main trouble (you have the answer, i know!) :
    suppose i have a class, with methods that should process ANY kind of object given. and - i don't know which. i only get it at runtime from an unknown source.
    let's say: public void BlackBox( Object x );
    inside, i know that there might be regular objects or arrays, and for this case i have some special hidden method, just for arrays... now try to find it out:
    public void BlackBox( Object x )
      if ( x == null)
           return;
       Class c = x.getClass();
       if ( c.isArray() )
              // call the array method if it's an array.........
              BlackBoxes(     (Object [] )  x );         // wait: this is a cast! and it WILL throw an exception, eventually!
              return;
       else
               DoSpecialStuffWith( x );
    }ok ? now, to process any kind of array, the special method you cannot reach from outside:
    private void BlackBoxes( Object[] xs )
       if ( xs != null )
            for ( Object x : xs )
                 BlackBox( x );
    // this will end up in some kind of recursion with more than one array-dimension, or when an Object[] has any other array as element!this approach is perfectly save when processing any (real) Object, array or "multi-dimensional" arrays of Objects.
    but, you cannot use this with primitive type arrays.
    using generics wouldn't help, because internally it is all downcasted to Object.
    BlackBox( new Integer(3) ) ---- does work, using a wrapper class
    BlackBox( new Integer[3] ) ----- yep!
    BlackBox( 3 ) ---- even this!
    BlackBox( new int[42] ) ---- bang! ClassCastException, Object[] != int[]
    i'm stuck. i see no way to do this smoothly. i could write thousands of methods for each primitive array - BlackBox( int[] is ) etc. - but this wouldn't help. because i can't cast an int[][] to int[], i would also have to write countless methods for each dimension. and guess, how much there are?
    suppose, i ultimately wrote thousands of possible primitive-type methods. it would be easy to undergo any of it, writing this:
    BlackBox( (Object) new int[9] [9] );
    the method-signature would again only fit to my first method, so the whole work is useless. i CAN cast an int[] to Object, but there seems no convenient way to get the real array out of Object - in a generic way.
    i wonder, how do you write a serialisation-engine? and NO, i can't rely on "right usage" of my classes, i must assume the worst case...
    any help appreciated!

    thanks, brigand!
    your code looks weird to me g and i think there's at least one false assumption: .length of a multidimensional array returns only the number of "top-level" subarrays. that means, every length of every subarray may vary. ;)
    well i guess i figured it out, in some way:
    an int is no Object;
    int[ ] is an Object
    the ComponentType of int [ ] is int
    so, the ComponentType of an Object int[ ] is no Object, thus it cannot be casted to Object.
    but the ComponentType of int [ ] [ ] IS Object, because it is int [ ] !
    so every method which expects Object[], will work fine with int[ ] [ ] !!
    now, you only need special treatment for 1-dimensional primitive arrays:
    i wrote some code, which prints me everything of everything:
        //this method generates tabs for indentation
        static String Pre( int depth)
             StringBuilder pre = new StringBuilder();
             for ( int i = 0; i < depth; i++)
                  pre.append( "\t" );
             return pre.toString();
        //top-level acces for any Object
        static void Print( Object t)
             Print ( t, 0);
        //the same, but with indentation depth
        static void Print( Object t, int depth)
            if ( t != null )
                 //be shure it is treated exactly as the class it represents, not any downcast
                 t = t.getClass().cast( t );
                if ( t.getClass().isArray() )
                     //special treatment for int[]
                     if ( t instanceof int[])
                          Print( (int[]) t, depth);
                     // everything else can be Object[] !
                     else
                          Print( (Object[]) t, depth );
                     return;
                else
                    System.out.println( Pre(depth) + " [ single object:] " + t.toString() );
            else
                System.out.println( Pre(depth) + "[null!]");
        // now top-level print for any array of Objects
        static void Print( Object [] o)
             Print( o, 0 );
        // the same with indentation
        static void Print( Object [] o, int depth)
            System.out.println( Pre(depth) + "array object " + o.toString() );
            for ( Object so : o )
                    Print( so, depth + 1 );
        //the last 2 methods are only for int[] !
        static void Print( int[] is)
             Print( is, 0 );
        static void Print( int[] is, int depth)
            System.out.println( Pre(depth) + "primitive array object " + is.toString() );
            // use the same one-Object method as every other Object!
            for ( int i : is)
                 Print ( i, depth + 1 );
            System.out.println( "-----------------------------" );
        }now, calling it with
    Print ( (int) 4 );
    Print ( new int[] {1,2,3} );
    Print( new int[][] {{1,2,3}, {4,5,6}} );
    Print( new int[][][] {{{1,2,3}, {4,5,6}} , {{7,8,9}, {10,11,12}}, {{13,14,15}, {16,17,18}} } );
    Print( (Object) (new int[][][][] {{{{99}}}} ) );
    produces this fine array-tree:
    [ single object:] 4
    primitive array object [I@9cab16
          [ single object:] 1
          [ single object:] 2
          [ single object:] 3
    array object [[I@1a46e30
         primitive array object [I@3e25a5
               [ single object:] 1
               [ single object:] 2
               [ single object:] 3
         primitive array object [I@19821f
               [ single object:] 4
               [ single object:] 5
               [ single object:] 6
    array object [[[I@addbf1
         array object [[I@42e816
              primitive array object [I@9304b1
                    [ single object:] 1
                    [ single object:] 2
                    [ single object:] 3
              primitive array object [I@190d11
                    [ single object:] 4
                    [ single object:] 5
                    [ single object:] 6
         array object [[I@a90653
              primitive array object [I@de6ced
                    [ single object:] 7
                    [ single object:] 8
                    [ single object:] 9
              primitive array object [I@c17164
                    [ single object:] 10
                    [ single object:] 11
                    [ single object:] 12
         array object [[I@1fb8ee3
              primitive array object [I@61de33
                    [ single object:] 13
                    [ single object:] 14
                    [ single object:] 15
              primitive array object [I@14318bb
                    [ single object:] 16
                    [ single object:] 17
                    [ single object:] 18
    array object [[[[I@ca0b6
         array object [[[I@10b30a7
              array object [[I@1a758cb
                   primitive array object [I@1b67f74
                         [ single object:] 99
    -----------------------------and i'll have to write 8 methods or so for every primitive[ ] type !
    sounds like a manageable effort... ;-)

  • Dynamic class loading and Casting

    Hi guys,
    spent lots of time trying to figure out how to do one thing with no luck, hope anybody can help me here. Here is what I have:
    I need to create a new object, I have dynamic variable of what kind of an object I need:
    sObjectType = "Article";
    ItemObject oItem = Item.init(1000, 1);           
    oItem.ArticleObjectCall();                      // ERROR is here, method does not exist, ArticleObjectCall is method of the Article classItem is a static Class that inits objects
    public class Item {
         public static ItemObject init(String sObjectType) {
                  ItemObject oClass = Class.forName("com.type." + sObjectType).newInstance();
                  return oClass;
    }Below are the 2 classes Article and ItemObject
    Article
    package com.type;
    public class Article extends ItemObject {     
         public void ArticleObjectCall() {
              System.out.println("Article Hello");
    ItemObject
    public class ItemObject {
         public ItemObject() {          
    }

    Ajaxian wrote:
    This is a method INIT, I am dynamically including class com.type.Article , Article extends ItemObject, I am casting new instance of Article to (ItemObject) to return a proper type but later when I try to call oClass object which is I believe my Article class, I get an error. None of which answers my question, yet it does show that you are thoroughly confused...
    String x = "blub";
    Object y = x;
    System.out.println(y.length); // We both know y is a string, but the compiler does not. => ErrorThe compiler enforces the rules of a static type system, your question is quite explicitly about dynamism, which is not without reason the antonym to statics. If you load classes dynamically, you need to use reflection to invoke their methods.
    With kind regards
    Ben

  • ORA-22905 and Cast function

    I am running a query with following code:
    select d.acct_num, lib.fmt_money(a.amt) Total Amount
    from account d, table(report.lib.expense (d.acct_num)) a
    where clause.
    Here:
    1. Report is another schema containing packqges for reporting development.
    2. lib is package name created in the report schema. It contains function such as expense.
    3. expense is a function under Lib package as
    function expense (p_acct number) return number is
    acct_num number;
    begin select xxxx into acct_num from xxx_table); return nvl(acct_num, 0);
    end expense;
    Then when I run this select statement, it gave me ORA-22905 error. Cause: attempt to access rows of an item whose type is not known at parse time or that is not of a nested table type. Action: use CAST to cast the item to a nested table type.
    I used CAST like this:
    select d.acct_num, CAST(a.amt as number ) Total Amount
    from account d, table(report.lib.expense (d.acct_num)) a
    where clause.
    It gave me ORA-00923 From keyword not found where expected.
    Please help me to find where the problem is and thank you for your help a lot.

    citicbj wrote:
    I have checked function and found that function was defined as this:
    function expense (p_exp varchar2) return number
    is
    l_exp number;
    begin
    select xxx into l_exp from xxxx where clause;
    return nvl(l_exp, 0);
    end expense;
    So this is not defined as the table of array. So I take the table off from select statement as
    select d.acct_num,
    to_number(a.amt) Total Amount
    from account d,
    report.lib.expense (d.acct_num) a
    where d.acct_num = a.acct_num;
    Then it return ORA-00933 SQL command not ptoperly ended. However, I couldn't see any not properly ended SQL code here. Please advise your comments.Should just be ...
    select
       d.acct_num,
       report.lib.expense (d.acct_num) as "Total Amount"
       --to_number(a.amt) Total Amount
    from account dNotice that i enclosed the column alias (Total Amount) in " ... that is because you can't have a column alias with spaces as you tried without doing this (the parser gets sad).
    Also, you cannot use a function returning a single value like this as a nested table (at least not the way you are trying) and in your case there's no reason. You don't want to join to it, you are passing in ACCT_NUM which the function will presumably use to filter out not relevant data.
    Finally, there's no reason to TO_NUMBER the function result ... it's already defined to return a number :)

  • DefaultMutableTreeModel, and casting TreeModel - DefaultMutableTreeModel

    I have a workflow object, from which I create a workflowTreeModel and display this in a JTree - all works OK....
    I now need to create a DefaultMutableTreeModel from the same workflow object and I in need of some pointers. (please)
    All the examples I can find create a number of DefaultMutableTreeNodes (eg, red, blue, green) and add them to a DefaultMutableTreeNode (eg.color)...
    As I already have a workflow object that I am trying to display this approach doesn't fit. Is there anyway to create a DefaultMutableTreeModel in the same way as I am creating the TreeModel?
    Looking at the 'understanding the treeModel' tutorial from Sun I see that I should be able to cast my workflowTreeModel to a DefaultTreeModel using:
    JTree() myTree = new JTree(workflowTreeModel);
    DefaultTreeModel t = (DefaultTreeModel) myTree.getModel();
    However I get a class cast exception trying to do this - I imagine this is as a result of the way the workflowTreeModel is created (code below).
    If anyone can show me the correct way to create a DefaultTreeModel from my workflow object I would be grateful....
    (workflowTreeModel code: )
    public class WorkflowTreeModel extends AbstractWorkflowTreeModel {
         * Commons Logger for this class
        private static final Log logger = LogFactory.getLog(WorkflowTreeModel.class);
        private Workflow rootWorkflow;     
         public WorkflowTreeModel(Workflow root) {
              rootWorkflow = root;
         /* (non-Javadoc)
          * @see javax.swing.tree.TreeModel#getRoot()
         public Object getRoot() {
              return rootWorkflow.getSequence();
         /* (non-Javadoc)
          * @see javax.swing.tree.TreeModel#getChildCount(java.lang.Object)
         public int getChildCount(Object parent) {
              int i = 0;
              if(parent instanceof Workflow) {
                   i = 1;
              else if(parent instanceof Sequence) {
                   Sequence s = (Sequence)parent;
                   i = s.getActivityCount();
              else if(parent instanceof Flow) {
                   Flow f = (Flow)parent;
                   i = f.getActivityCount();
              else if(parent instanceof For) {
                   For f = (For)parent;
                   Sequence s = (Sequence)f.getActivity();
                   i = s.getActivityCount();
              else if (parent instanceof If) {
                   If a = (If)parent;
                   if (a.getElse() != null && a.getElse() instanceof Else)
                        i = i + 1;
                   if (a.getThen() != null && a.getThen() instanceof Then)
                        i = i + 1;
              else if (parent instanceof Else || parent instanceof Then) {
                 i = 1;
              else if (parent instanceof For || parent instanceof Parfor || parent instanceof While) {
                   i = 1;
              else if (parent instanceof Scope) {
                   i = 1;
              else if (parent instanceof Script) {
                   i = 1;
              return i;
         /* (non-Javadoc)
          * @see javax.swing.tree.TreeModel#isLeaf(java.lang.Object)
         public boolean isLeaf(Object node) {
              boolean b = true;
              if (node instanceof Sequence) {
                   if (((Sequence)node).getActivityCount() > 0)
                        b = false;
              if (node instanceof Flow) {
                   if (((Flow)node).getActivityCount() > 0)
                       b = false;
              else if (node instanceof If || node instanceof Else || node instanceof Then) {
                   b = false;
              else if (node instanceof For || node instanceof Parfor || node instanceof While) {
                   b = false;
              else if (node instanceof Scope) {
                   b = false;
              else if (node instanceof Workflow) {
                   b = false;
              else if (node instanceof Script) {
                   b = false;
              return b;
         /* (non-Javadoc)
          * @see javax.swing.tree.TreeModel#addTreeModelListener(javax.swing.event.TreeModelListener)
         public void addTreeModelListener(TreeModelListener l) {
         /* (non-Javadoc)
          * @see javax.swing.tree.TreeModel#removeTreeModelListener(javax.swing.event.TreeModelListener)
         public void removeTreeModelListener(TreeModelListener l) {
         /* (non-Javadoc)
          * @see javax.swing.tree.TreeModel#getChild(java.lang.Object, int)
         public Object getChild(Object parent, int index) {
              Object ob = null;
              if (parent instanceof Workflow){
                   Workflow w = (Workflow)parent;
                   ob = w.getSequence();
              else if(parent instanceof Sequence) {
                   Sequence s = (Sequence)parent;
                   ob = s.getActivity(index);
              else if(parent instanceof Flow) {
                   Flow f = (Flow)parent;
                   ob = f.getActivity(index);
              else if (parent instanceof For) {
                   For f = (For)parent;
                   Sequence s = (Sequence)f.getActivity();
                   ob = s.getActivity(index);
              else if (parent instanceof Parfor) {
                   Parfor p = (Parfor)parent;
                   ob = p.getActivity();
              else if (parent instanceof Scope) {
                   Scope s = (Scope)parent;
                   ob = s.getActivity();
              else if (parent instanceof While) {
                   While w = (While)parent;
                   ob = w.getActivity();
              else if (parent instanceof If) {
                   If i = (If)parent;
                   if (index == 0) {
                        if ((i.getThen() != null) && (i.getThen() instanceof Then)){
                             ob = i.getThen();
                        else if ((i.getElse() != null) && (i.getElse() instanceof Else)){
                             ob = i.getElse();
                   if (index == 1) {
                        if ((i.getElse() != null) && (i.getElse() instanceof Else)){
                             ob = i.getElse();
                        else if ((i.getThen() != null) && (i.getThen() instanceof Then)){
                             ob = i.getThen();
              else if (parent instanceof Else) {
                   Else e = (Else)parent;               
                   ob = e.getActivity();               
              else if (parent instanceof Then) {
                   Then t = (Then)parent;               
                   ob = t.getActivity();               
              else if (parent instanceof Script) {
                   Script s = (Script)parent;
                   ob = s.getBody();
              return ob;
         /* (non-Javadoc)
          * @see javax.swing.tree.TreeModel#getIndexOfChild(java.lang.Object, java.lang.Object)
         public int getIndexOfChild(Object parent, Object child) {
              logger.debug("getIndexOfChild");
              // TODO Auto-generated method stub
              return -1;
         /* (non-Javadoc)
          * @see javax.swing.tree.TreeModel#valueForPathChanged(javax.swing.tree.TreePath, java.lang.Object)
         public void valueForPathChanged(TreePath path, Object newValue) {
              // TODO Auto-generated method stub
    public abstract class AbstractWorkflowTreeModel extends WorkflowTreeModelSupport implements TreeModel {
    }

    JTree() myTree = new JTree(workflowTreeModel);
    DefaultTreeModel t = (DefaultTreeModel) myTree.getModel();the only way you can cast this is that workflowTreeModel must extends DefaultTreeModel
    What you can do is to for WorkFlowTreeMdeol to extends DefaultTreeModel
    or case it to WorkFlowTreeModel
    JTree() myTree = new JTree(workflowTreeModel);
    WorkFlowTreeModel model = (WorkFlowTreeModel) myTree.getModel();

  • How to test and cast an object to a generic

    Hi all,
    my problem is the following:
    I have a list of notifications from a transaction listener of the Eclipse Modeling Framework.
    Each element of that list is of type Notification, but I have to cast it to something else to work with it since it is pretty useless by itself.
    I need to test if it is a certain generic type (+NotifyingListImpl<?>+) but of course I can't use the instanceof test. Is there a way to solve the problem?
    Bear in mind that I googled a lot and tried a lot of solutions without success before asking this question (which I hope it is a piece of cake for an
    java expert :-) )
    As a side problem I don't know the actual type of the generic since I gathered all the information using the Eclipse debug, and the debug
    says my notification is of type NotifyingListImpl$1, I figured out the parameter of that type is ResourceImpl since the inspection of the
    notification's list of fields contains a this$0 of that type. Is my intuition about the Eclipse debug correct?

    I need to test if it is a certain generic type (+NotifyingListImpl<?>+) but of course I can't use the instanceof test.Yes you can:
    if (object instanceof NotifyingListImpl) { ... }
    As a side problem I don't know the actual type of the genericYou can't. It is erased to the lower bound at compile time.
    since I gathered all the information using the Eclipse debug, and the debug
    Is my intuition about the Eclipse debug correct?It has nothing to do with Eclipse debug. The information isn't available. It was erased by the compiler.

  • Parent class and Casting

    Hi all,
    I need to store different classes in a Vector. The classes have in common that they are all different views (MVC!). If I make a common parent, can I cast to that parent without problems?
    Background:
    I'm programming on a mobile, which uses different screens (choice screen, data screen and help screen). Depending on an event, be it a button pressed, or data comming in from another mobile, the view the player gets needs to be changed. The Model will call an update () method on the view. If I make the update method abstract, the update method of the child class will be used?
    Maik

    I need to store different classes in a Vector. The
    classes have in common that they are all different
    views (MVC!). If I make a common parent, can I cast
    to that parent without problems?Yes.
    If I make the update
    method abstract, the update method of the child class
    will be used? Is there any other? It will always use the method the instance implements.

  • Polymorphism and inheritance

    Just want to make sure I have a few things straight:
    If I extend a full class, I'm demonstrating inheritance.
    If I extend an abstract class (as a result, I need to override the abstract methods to provide implementations) I'm demonstrating polymorphism, though any class variables from the abstract class are INHERITED by my new class.
    If I implement an interface, I'm exercising polymorphism.
    Am I correct on all fronts?

    Normally from an OO perspective there are twotypes
    of polymorphism:-I've always found the classification of polymorphism
    into static vs. dynamic kind of stupid. What does itWell its a free country, you have every right to feel that way.
    matter whether methods are bound at compiletime or at
    runtime? It's an implementation detail of little
    importance. This classification doesn't offer anyI personally however found this particular detail of significant importance in how the different patterns work. However for somebody more interested in syntax than the semantics, yes it is of little importance.
    deeper understanding of the difference between method
    overloading and method overriding. The former is
    bound at compiletime and the latter at runtime. So
    what? But it's good chanting material of course -:)

Maybe you are looking for