Subclassing NSControl or NSView

Hi,
I have written an extension to an open source application which has a widget that is subclassing NSControl. This all worked fine on Tiger.
In Tiger I could override setTarget and setAction and hook my control up to the main File Owner using the control drag in IB to get callbacks from it using something like
[self sendAction:[self action] to:[self target]];
I have taken the same code and tried to port to Leopard (don't have the Tiger install anymore) and I cannot get the new IB to allow me to do this.
Just fyi, the control wants to send mouse-over-object events to the owner which can then take some action depending on what object the mouse is actually over. The control is implementing some pretty specific drawing, layout and mouse-dragging logic around some static images. Everything is working fine as is, except for getting this event to the main controller.
I tried looking for some examples that are subclassing NSView/NSControl and found the ClockControl example which I previously got to work on Tiger, but not yet on Leopard. Does this work on Leopard?
Where can I find out what to try next? How do another subclasses of NSControl (e.g. NSButton) get IB to recognise that it is a source of events and thus a drop target for the control-drag in IB to hook stuff up?
Any help or suggestions more than welcome (note I am pretty new to Cocoa and OSX, only been going for about 9 months).
Thanks,
David.

I didn't know (Nor do I know where to have found) that NSAffineTransform in objective C is just a wrapper for a bunch CGAffineTransform functions in C. Interesting.
In any case, I'm pretty sure that that isn't the problem because I can actually look at the transformation matrix, and it is correct. My question is why on some calls to drawRect: the transform gets correctly executed, but on others the exact same matrix gets either wholly, or partially ignored. Why from one call to the big private method above, the translate works, but the scale doesn't, and in another everything works...

Similar Messages

  • Cocoa app design advice

    hello,
    as i'm studying cocoa i've created a test app and i'm looking for some advice/direction when it comes to design. this is what i've done so far:
    1. placed a custom view on my main window linked to my custom subclass "dropview" of nsview
    2. placed a table view on my main window linked to a "appcontroller" object
    with the custom view i can accept drags and when i do i use a nstask method to search for files and place these files in an array. then i want to display these files in my table view. here are my questions: since the array variable is defined in my nsview subclass what is the right way to send that information to my appcontoller object? so far i have made a declaration of this variable above the @interface dropview and used #import dropview.h in my appcontroller.m file. then when the app launches it tries to set the table view from the start before my array variable is defined, but once the array variable is defined how do i tell the table view to update? i have tried to tell my table view to reloaddata from my dropview class but the table view is linked to my appcontroller class. i hope this makes sense and any advice on how i will communicate between the 2 classes is greatly appreciated!
    thank you,
    rick

    You should create one servlet, which accepts the params of any form and passes them to the backend.
    In summary:
    The one servlet is a 'controller' servlet ( the 'C' in MVC design).
    It takes in all url requests for all JSP pages (never allow a user to directly call up a JSP page) or from a submit from a form tag on any JSP page, or from a click on a hyperlink. It verifies the person is logged in (authenticated) and has permission to view the JSP page it wants to view (authorization). If its not authenticated or authorized, it dispatches to an error page. If it is, it determines what JSP page the request is comming from and what it wants (example: update button was clicked). It then instansiates business logic and sends the JSP page's information to it. The business logic performs the work. The data coming back from the business logic is put in request scope by the servlet (not by the business logic) and the servlet dispatches to the appropriate JSP page (which will get data out of request scope to be displayed).

  • NSView subclass and mouse clicks

    I wrote a relatively simple program. It's got a single visual component on the window, an NSView subclass with drawing delegated out to another class called Arrow. Anyway, it uses a timer to trigger calls to drawRect which in turn "animates" a layer. I have a 100x100 layer and a velocity & position which get updated each time through depending on how much "real" time has passed. As the layer bounces around the screen, the animation seems smooth and everything looks good. If I start clicking in the window, however, things get wonky. The animation stutters (probably expected) and the position sometimes gets set back to the origin (0,0, bottom left corner of screen). I wonder if there's something I can do to stop mouse clicks from affecting the view, I have no set up anything to use the mouse clicks AT ALL so I don't really know how they can affect anything in the code I wrote. If this isn't enough info to answer the question, I'll post the xcode project.

    The end result is going to be a very simple 2d game with maybe 8-10 things on the screen moving around at any one time. My next step is to try out openGL but using these CALayers seemed a lot simpler. However, since you say any event will block, I expect that will happen to opengl as well. I'll dig some more in the examples. It seems I followed the pattern from the crash landing demo (although I'm doing it on the mac itself, not iphone/simulator) to set up the rendering.
    When you suggest using core animation, are you talking about just telling it the start/end position and the speed, and letting it handle everything in between? I don't think that will work for my case because eventually I will have to handle mouse/keyboard events to alter the movement in real-time. Am I missing something?
    Thanks again for your help.

  • Saving NSView to Bitmap - (ScrollView)

    I have an NSView subclass called StretchView. Here's what I want to do: Since the StretchView has scrollbars and is extended via those scrollbars I want to be able to grab the entire StretchView (including the area not visible on screen) and save that to a file.
    // StretchView.h
    #import <Cocoa/Cocoa.h>
    @interface StretchView : NSView {
    -(IBAction)saveImageButtonPushed(id)sender;
    @end
    // StretchView.m
    #import "StretchView.h"
    @implementation StretchView
    -(IBAction)saveImageButtonPushed(id)sender
    NSLog(@"saveImageButtonPushed");
    NSBitmapImageRep *rep;
    NSData *data;
    NSImage *image;
    [self lockFocus];
    rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:[self frame]];
    [self unlockFocus];
    image = [[[NSImage alloc] initWithSize:[rep size]] autorelease];
    [image addRepresentation:rep];
    data = [rep representationUsingType: NSPNGFileType properties: nil];
    //save as png but failed
    [data writeToFile: @"asd.png" atomically: NO];
    //save as pdf, succeeded but with flaw
    data = [self dataWithPDFInsideRect:[self frame]];
    [data writeToFile:@"asd.pdf" atomically:YES];
    @end
    The problem is, the png file that generated is only part of the ScrollView (I tried to change the "initWithFocusedViewRect:[self frame]];" to "initWithFocusedViewRect:[self bounds]];" but in vain).
    Then I tried to save the NSView content as pdf file and this time the whole view content was grabbed successfully but the backgound color was gone(I've set the content view's background as red but in the pdf file the background was white).
    Can anybody give a hint, thans^_^

    Hello Ori,
    There is an example in the National Instruments example program database
    that does this. It seems that CVI 5.x does not have a function that saves a
    bitmap
    to a file. But this example does exactly that.
    check it out at the following page:
    http://digital.ni.com/explprog.nsf/2222373937d4e9a​38625666a00831a24/b1384a94
    02f57b13862564c80053702c?OpenDocument
    If the link is broken, go to http://www.ni.com/support/ and then go to
    the Example programs database. I used the following search string
    "cvi and file and bitmap".
    Good luck,
    Azucena
    "Ori Idan" wrote in message
    news:[email protected]..
    > I have an image on canvas indicator and I would like
    > to be able to save it into a bitmap file using LabWindows/CVI 5.0.1.
    >
    > Any advice?
    > Thanks,
    >
    > --
    > Ori Idan
    > Helicon technologies LTD. National Instruments Alliance member in ISRAEL
    >
    > Email: [email protected]
    > Home page: http://www.helicontech.co.il
    > Tel: +972-6-6262353 Fax: +972-6-6262405
    > ++++++++++++++++++++++++++++++++++++++++++++++++++​++++++++++++
    > Things should be made as simple as possible but not simpler
    > Albert Einstein
    > ++++++++++++++++++++++++++++++++++++++++++++++++++​++++++++++++
    >
    >

  • Help needed with basic implementation of drawrect: in NSView

    i've read the sections concerning the above in the "view guides for cocoa" docs, as well as several tutorials, but for the life of me i can't figure out how to do a very simple thing.
    all the examples i've seen explain how to use NSRect and NSBezierPath, with fills and strokes, *from within* the drawRect: method. but i want to pass a custom object as a method argument to the view object (say, from inside my controller object when a user presses a button), and then write the code needed to run some getters on the object and draw some stuff accordingly.
    i've defined the view as follows in the controller class header:
    MyCustomNSViewSubclass *theView;
    now i just want to send that view a message like this:
    [theView draw: myObject]
    then i just want to add the code in the view class to do find out some things about myObject and then draw some lines. i just don't understand where to put that code and how the drawRect: method gets called. writing a method like this in the MyCustomNSViewSubclass implementation (which is instanced in "theView") doesn't help:
    - (void) draw: (myObjectType *) anObject
    because then i can't figure what's needed to actually update the view.
    i understand i must be using a wrong approach here. any help will be much appreciated.
    thanks.

    No no, you didn't really understand : you are the developer, you do whatever you want, it means that if you want your custom NSView to simply ask other object to draw their own contents and do nothing else in the NSView you can, but if you want your NSView to manage everything you can too...
    For example, let say I want a Shape class to manage... Shapes in my views... That's not very useful since there's already the NSBezierPath class that allows you to draw a lot of things, but whatever.
    That shape class is very simple, it can represent either a rectangle or a circle and it can draw itself. There's the possible implementation :
    // Shape.h
    #import <Cocoa/Cocoa.h>
    @interface Shape : NSObject
    NSRect rect;
    NSColor *fillColor;
    NSColor *strokeColor;
    BOOL isCircle;
    - (void)setRect:(NSRect)aRect;
    - (void)setFillColor:(NSColor *)aColor;
    - (void)setStrokeColor:(NSColor *)aColor;
    - (void)setIsCircle:(BOOL)flag;
    - (void)draw;
    @end
    // Shape.m
    #import "Shape.h"
    @implementation Shape
    - (void)setRect:(NSRect)aRect
    rect = aRect;
    - (void)setFillColor:(NSColor *)aColor
    if(fillColor != aColor)
    [fillColor release];
    fillColor = [aColor retain];
    - (void)setStrokeColor:(NSColor *)aColor
    if(strokeColor != aColor)
    [strokeColor release];
    strokeColor = [aColor retain];
    - (void)setIsCircle:(BOOL)flag
    isCircle = flag;
    - (void)draw
    NSBezierPath *temp;
    if(isCircle)
    temp = [NSBezierPath bezierPathWithOvalInRect:rect];
    else
    temp = [NSBezierPath bezierPathWithRect:rect];
    [fillColor set];
    [temp fill];
    [strokeColor set];
    [temp stroke];
    - (void) dealloc
    [fillColor release];
    [strokeColor release];
    [super dealloc];
    @end
    That's a very simple class, there's not even an initializer... But it's not the problem here... What we want here it's a self-drown object. You see that class is a subclass of NSObject, nothing special.
    Let see now our custom NSView class, which means a subclass of NSView :
    // MyView.h
    #import <Cocoa/Cocoa.h>
    @class Shape;
    @interface MyView : NSView
    NSMutableArray *shapesToDraw;
    - (void)addShape:(Shape *)aShape;
    - (void)removeShapeAtIndex:(unsigned)index;
    @end
    // MyView.m
    #import "MyView.h"
    #import "Shape.h"
    @implementation MyView
    - (id)initWithFrame:(NSRect)frame
    self = [super initWithFrame:frame];
    if (self)
    // Here we simply create a new array that will contain our shapes to draw
    shapesToDraw = [[NSMutableArray array] retain];
    return self;
    - (void)drawRect:(NSRect)rect
    // This code simply asks to every shape in the array to draw itself
    NSEnumerator *e = [shapesToDraw objectEnumerator];
    Shape *shape = nil;
    while(shape = [e nextObject])
    [shape draw];
    - (void)addShape:(Shape *)aShape
    [shapesToDraw addObject:aShape];
    // When the content of the array changes, we need to tell the view
    // to redraw itself, we do with that message
    [self setNeedsDisplay:YES];
    - (void)removeShapeAtIndex:(unsigned)index
    [shapesToDraw removeObjectAtIndex:index];
    [self setNeedsDisplay:YES];
    - (void) dealloc
    [shapesToDraw release];
    [super dealloc];
    @end
    So you see here, how do you draw objects ? Well, first you need to know them, you also need them to know how to draw themselves... In Cocoa that kind of object already exists, they're NSBezierPath, when you send the message -fill or -stroke you ask them to draw themselves with the current color.
    Here, each shape will be asked one after another to draw itself in the rectangle that is defined in it. You can add a shape by creating it in a controller for example, and add it using the add method I defined, here the drawing code is actually in both classes, in fact we can consider [shape draw] as being "drawing code", that' a point to get : You can't draw outside a -drawRect: method (except in certain complex cases), but you can send messages that contains drawing code within -drawRect: to other objects. that's what I do here.
    However, you need to know that an NSView doesn't only manage its drawings, it also receives events like a click of the mouse or a typed key, there's methods to manage that into the view, and if all the code of an application is inside your view class, well your code might get really big and very difficult to read, that's why we cut in smaller parts to make it easier to read and to understand.
    So, do whatever you want in that -drawRect: method, you know, here I put a -draw method into the Shape class, but I could also have put method to get the NSRect value, the fill color, the stroke color and the kind of shape and make the drawing code directly in the view. You can do whatever you want.
    So, to summarize, you don't "send" objects for your view to draw. The view draws what the -drawRect: methods draws, and not more so if you want your view to draw custom paths, you can use the technic I gave you, that is for example you put a NSMutableArray into your view and create a ColoredPath class that own an NSBezierPath and two NSColor (fill and stroke) and you define a -draw method that your view will call on each ColoredPath objects that the array contains.
    That's a work around. But depending in what you actually want to do, there's a lot of different solutions.
    Now, talking about the interface problem. In IB when you drag a custom view on the window, by default that object is set to NSView, so you need to make it an instance of your own view subclass.
    If you're under Leopard with Xcode 3 and IB 3, in IB you click on your view and go in Identify Inspector (cmd + 6) you type the name of your subclass in the Class field, if you already created the class files, the name should appear before you finished.
    If you're under Xcode 2 and IB 2, you go in the Custom Class Inspector (also cmd + 6) and you select your custom class in the list.
    The name of your class should replace the "Custom Class" label on the view.
    That's how you set the class of a view in IB and make your app call your code when the view needs to display.

  • Mouse dragging events in NSWindow and NSView

    Hi, I have built and application that uses a single window that contains multiple components within it. The main component of the window is a custom NSView subclass that contains a number of CALayers. I want to be able to move these layers around the NSView subclass based on the mouseDown, mouseDragged, and mouseUp events entered by the user. I can detect and process mouse events fine within the NSView subclass, however, whenever I drag the mouse within the NSView subclass right after a mouseDown event, the WHOLE WINDOW will move. I do not want that to happen, that is, when I am dragging the mouse within my NSView subclass, I do not want the whole window to move. I want my CALayers, within the NSView, to move according to the mouse events that I am correctly tracking in the NSView subclass. I will very much appreciate any suggestions. Thank you very much in advance.

    Thank you very much for your response. Your tip is very useful. What I did before was change the window type in Interface Builder: replace the textured window with a regular window. This solved the problem, however, I could not find the property that needed to be adusted to control the window behavior. I learned something useful with your tip. Thanks again.

  • NSButton subclassing

    Hi,
    I want to set Button's Cell class to may custom subclass of NSButtonCell Class. NSControl class has method +setCellClass. how should i use this method. I tried to use in awakeFromNib but get exception. where should i use this. My application has many buttons it is not feasible me to set buttoncell class from IB. can i do this from code?
    Thanks

    Hey,
    Thanks, After digging a little bit - it is solved !
        postinit {
            var tbSkin = skin as com.sun.javafx.scene.control.caspian.TextBoxSkin;
            tbSkin.paddingLeft   = 30;  // default: 4
            //tbSkin.paddingTop    = 8;  // default: 4
            //tbSkin.paddingBottom = 8;  // default: 4
            tbSkin.paddingRight  = 30;  // default: 4
        }--Seb                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Error while calling a super class public method in the subclass constructor

    Hi ,
    I have code like this:
    CLASS gacl_applog DEFINITION ABSTRACT.
      PUBLIC SECTION.
        METHODS:
                create_new_a
                   IMPORTING  pf_obj       TYPE balobj_d
                              pf_subobj    TYPE balsubobj
                              pf_extnumber TYPE string
                   EXPORTING  pfx_log_hndl TYPE balloghndl
                   EXCEPTIONS error
    ENDCLASS.
    CLASS gacl_applog IMPLEMENTATION.
      METHOD create_new_a.
        DATA: ls_log TYPE bal_s_log.
      Header aufsetzen
        MOVE pf_extnumber TO ls_log-extnumber.
        ls_log-object     = pf_obj.
        ls_log-subobject  = pf_subobj.
        ls_log-aluser     = sy-uname.
        ls_log-alprog     = sy-repid.
        ls_log-aldate     = sy-datum.
        ls_log-altime     = sy-uzeit.
        ls_log-aldate_del = ls_log-aldate + 1.
        CALL FUNCTION 'BAL_LOG_CREATE'
             EXPORTING
                  i_s_log      = ls_log
             IMPORTING
                  e_log_handle = pfx_log_hndl
             EXCEPTIONS
                  OTHERS       = 1.
        IF ( sy-subrc NE 0 ).
          MESSAGE ID      sy-msgid TYPE sy-msgty NUMBER sy-msgno
                  WITH    sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4
                  RAISING error.
        ENDIF.
      ENDMETHOD.
    CLASS gcl_applog_temp DEFINITION INHERITING FROM gacl_applog.
      PUBLIC SECTION.
        DATA: log_hndl   TYPE balloghndl READ-ONLY
            , t_log_hndl TYPE bal_t_logh READ-ONLY
        METHODS: constructor
                   IMPORTING  pf_obj       TYPE balobj_d
                              pf_subobj    TYPE balsubobj
                              pf_extnumber TYPE string
                   EXCEPTIONS error
               , msg_add      REDEFINITION
               , display      REDEFINITION
    ENDCLASS.
    CLASS gcl_applog_temp IMPLEMENTATION.
      METHOD constructor.
        CALL METHOD create_new_a
               EXPORTING  pf_obj       = pf_obj
                          pf_subobj    = pf_subobj
                          pf_extnumber = pf_extnumber
               IMPORTING  pfx_log_hndl = log_hndl.
        IF ( sy-subrc NE 0 ).
          MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
                  WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4
                  RAISING error.
        ENDIF.
      ENDMETHOD.
    A public method of Super class has been called from the constructor of the sub class. we are getting the syntax error :
    ' In the constructor method, you can only access instance attributes, instance methods, or "ME" after calling the constructor of the superclass…'
    Can you please suggest how to change the code with out affecting the functioanlity.
    Thank you ,
    Lakshmi.

    Hi,
    Call that method by instance of Subclass.   OR
    SUPER-->method.
    Read very useful document
    Constructors
    Constructors are special methods that cannot be called using CALL METHOD. Instead, they are called automatically by the system to set the starting state of a new object or class. There are two types of constructors - instance constructors and static constructors. Constructors are methods with a predefined name. To use them, you must declare them explicitly in the class.
    The instance constructor of a class is the predefined instance method CONSTRUCTOR. You declare it in the public section as follows:
    METHODS CONSTRUCTOR
            IMPORTING.. [VALUE(]<ii>[)] TYPE type [OPTIONAL]..
            EXCEPTIONS.. <ei>.
    and implement it in the implementation section like any other method. The system calls the instance constructor once for each instance of the class, directly after the object has been created in the CREATE OBJECT statement. You can pass the input parameters of the instance constructor and handle its exceptions using the EXPORTING and EXCEPTIONS additions in the CREATE OBJECT statement.
    The static constructor of a class is the predefined static method CLASS_CONSTRUCTOR. You declare it in the public section as follows:
    CLASS-METHODS CLASS_CONSTRUCTOR.
    and implement it in the implementation section like any other method. The static constructor has no parameters. The system calls the static constructor once for each class, before the class is accessed for the first time. The static constructor cannot therefore access the components of its own class.
    Pls. reward if useful....

  • How to get the subclass from a super class( or interface)

    hi,
    I want to get subclass from a super class (or a interface), how to do that? the subclass of a interface means the class implementing the interface.
    for example;
    List ls;
    I want to get the subclass of ls, i.e., LinkedList, Stack, Vector......
    AbstractList al;
    the subclass of al, i.e., ArrayList, Vector.......
    thanks
    Aiwu

    List ls = new ArrayList();Since ls has been declared as a List we can only use List methods
    with it. This is a good thing because we might later want to change
    it to some other sort of List.
    I want to get subclass from a super class (or a interface), how to do
    that?The instance of the subclass declared above did not really come
    from the super class. A class "knows nothing" about its
    subclasses: many sub classes would not even exist at the time
    the class was written.

  • How can I invoke a method on a subclass based on the runtime type?

    Hi all,
    I have defined a base class OrderDetail, and 2 subclasses which extend it: OrderDetailSingleReservation and OrderDetailMonthReservation. Furthermore, I have a method:
        public Order order_generate(OrderDetail orderDetail) {
            if (orderDetail instanceof OrderDetailSingleReservation) {
                return order_generate((OrderDetailSingleReservation) orderDetail);
            }  else if (orderDetail instanceof OrderDetailMonthReservation) {
                return order_generate((OrderDetailMonthReservation) orderDetail);
            } else {
                Misc.alert("orderAndInvoice_Generate(GENERIC): unsupported type.");
                return null;
        }The type of this method's parameter is OrderDetail, as you can see. (This particular method only serves as a kind of dispatcher and is therefore not very interesting in itself, but the same pattern using 'instanceof' occurs in a codebase I am working on several times, and I would like to factor it out if possible.)
    My question: it seems that the invocation of order_generate() from within this method requires an explicit downcast to one of the two subclasses. If not, java invokes the method on the superclass. But at runtime, the JVM knows what type of object it is dealing with, right? So is there no way to do this without the explicit downcast?
    A similar problem occurs when trying to invoke a method on an object whose type is one of the subclasses; the method on superclass is called, instead of the one in the appropriate subclass that overrides it.
    Any help would be greatly appreciated!
    Thanks,
    Erik

    Thanks for your replies! I was editing my post last night to clarify it, but my connection went down and the edit was lost :(
    Anyway, yes, it should be done with polymorphism. I was constructing an example using the famous Animal, Cat and Dog classes to demonstrate my question more clearly, and to my surprise the problem does not occur in my example code.
    LRMK: Invoking a method such as in your example, where the method is inside the class itself, works fine. However for MVC's sake, I have a separate class called Invoicing with methods as below:
    class invoicing
      // the method for the superclass
      public Invoice invoice_create(OrderDetail orderDetail) {
         System.out.println("type: " + orderDetail.getClass());
         return null;
      // the method for one of the subclasses (this method is being not invoked)
      public Invoice invoice_create(OrderDetailSingleReservation orderDetail) {
         return null;
      // ...nor is this one.
      public Invoice invoice_create(OrderDetailMonthReservation od) {
         return null;
    }Now I attempt to invoke these methods:
    // create example objects
    OrderDetailSingleReservation odSingle = new OrderDetailSingleReservation();
    OrderDetailMonthReservation odMonth = new OrderDetailMonthReservation();
    // this call displays "odSingle type: OrderDetailSingleReservation"
    System.out.println("odSingle type: " + odSingle.getClass());
    // this call displays "odMonth type: OrderDetailMonthReservation"
    System.out.println("odMonth type: " + odMonth.getClass());
    // this call invokes Invoicing.invoice_create(OrderDetail)
    // instead of Invoicing.invoice_create(OrderDetailSingleReservation)
    Invoicing.invoice_create(odSingle);
    // this call invokes Invoicing.invoice_create(OrderDetail)
    // instead of Invoicing.invoice_create(OrderDetailMonthReservation)
    Invoicing.invoice_create(odMonth);So these calls will invoke the method for the superclass, i.e. Invoicing.invoice_create(OrderDetail od). That method then then executes the System.out.println() call which displays the class type of its parameter as one of { OrderDetailSingleReservation | OrderDetailMonthReservation }, that is, the expected subclass types!
    So the dynamic dispatch isn't working the way I would expect it to. If I do the explicit if-else checking using instanceof, as described in my first post, the correct methods are called.
    I hope the problem is somewhat clearer now. I am a bit lost as to what might be causing this, or how to monitor what's going on inside the jvm. Any ideas? BTW, the OrderDetail class and its subclasses are JPA entities (though I don't think it should matter).
    Thanks!
    Erik

  • Unique methods in subclass: can't access if superclass was the cast

    Hey up,
    I have an abstract class - Boid - and two subclasses - PredatorBoid and PreyBoid.
    If I add a method to PreyBoid (not one that's over-riding a method from Boid: its unique to this class) something that confuses me occurs.
    I can access this method if I instantiate PreyBoid thus:
    PreyBoid p = new Preyboid();
    But how I want to instantiate it is as part of an array, thus:
    private Boid[] boids = new Boids[x];
    for (int i=0; i<numberOfBoids*2;i+=2) {
                boids[i] = new PreyBoid();
                boids[i+1] = new PredatorBoid();
            }But if make em this way, I can no longer access the method unique to PreyBoid.
    Am I missing something? Do I have to make two separate arrays for the different kind of boid (which somewhat defeats the point?)
    The alternative is to add abstract methods for every different subclass method - but given that some of them are unique to the subclasses, this seems like overkill and clutter.
    It also makes no difference if the superclass is abstract or not: if I start by casting the array as a Boid array, but fill it with sub-classes, I can only access the methods that have been over-ridden from the superclass.
    Any thoughts gratefully received! I have read plenty about this, but can't find an answer anywhere...

    You can cast them of course(see below). My advice is to use an ArrayList for each type. ArrayLists also resize dynamically and also support Generics which avoid casting. (Not in all Java versions though, 1.5 and upwards)
    ((PreyBoid)boids).getSomeValue();
    Message was edited by:
    helloWorld

  • How to create a UITableView subclass in Xcode 4?

    In Xcode 3 you can create a UITableView option while creating a new class. Now this option is gone and was replaced by an "iPad compatible" option. How can I get to the UITableView option? Or is there any other way to create an UITableViewController?

    Hey Elefantosque,
    I have been creating UITableView classes by doing the following:
    Select NewFile
    Select UIViewControllerSubclass and click Next
    Where it says 'subclass of', use the drop-down menu to select UITableViewController and click Next
    Enter your new file name and click Save.
    I hope this is what you are asking?
    james

  • How to call a subclass method.

    Hi:
    I am trying to call a method from the subclass. I get many errors. Please correct the following code.
    public abstract class A{
    private int id;
    public static void main(){
    A obj = new B(200);
    obj.subclassMethod;
    class B extends A{
    public void subclassMethod(){
    System.out.println("ID is : " +id);
    public B(int i){
    id = i;

    The first problem:
    A obj = new B(200);  // This is perfect
    obj.subclassMethod; // <--obj is an object of type "A" and "A" doesnt know "subclassMethod()"
    so in order to call "subclassMethod" you have to make a explicit casting to "B".
    ((B)obj).subclassMethod(); //remeber that calling a method needs "()"
    The second problem:
    System.out.println("ID is : " +id);You cannot acces a private variable or function from anywhere else but the class.
    If you want to acces you need to declare it:
    protected: for access from anywhere in the package and/or subclass(for your case i recomend this).
    public: for acces from anywhere.
    (nothing)package:(dont declare anything) acces for anywhere from the class.
    In resume:
    Change to the following lines to fix:
    private int id; // --> protected int id;
    obj.subclassMethod;  // --> ((B)obj).subclassMethod();I hope this help.
    N�stor Mata.

  • Why assigning a subclass instance to a variable of type of superclass ?

    Hi all,
    What is the significance of assigning an instance of a subclass to a variable whose type is a superclass's type.
    For eg. List list=new ArrayList();
    If I do so is it possible to execute the methods of the subclass ?
    regards
    Anto Paul.

    In addition, this is what polymorphism is all about:
    abstract class Animal {
      String name;
      Animal(String name) {
        this.name = name;
      public abstract void voice();
    class Dog extends Animal {
      Dog(String name) { super(name); }
      public void voice() {
        System.out.println(name+" barks");
    class Cat extends Animal {
      Cat(String name) { super(name); }
      public void voice() {
        System.out.println(name+" miaows");
    public class Polymorphism {
      public static void main(String args[]) {
        Animal[] animals = {
          new Dog("Fido"),
          new Cat("Felix")
        for (int i = 0; i < animals.length; i++) {
          animals.voice();
    Here, we are looping through an array of Animals. In fact, these are concrete subclasses of the abstract Animal class. In this simple example, you can see from the code that the animals array contains a dog and a cat. But we could even extend this to read in an arbitrary Animal object that had been serialized into a file. At compile time, the exact class of the serialized animal would not be known. But polymorphism occurs at runtime to ensure the correct voice() method is called.
    For the List, or Map example, conisder this:
    public SomeClass {
      public HashMap map1 = new HashMap();  // this ties you to hashmap
      public Map map2 = new HashMap();      // this allows you to change Map implementation
      public void process(HashMap map) {}   // this ties you to hashmap
      public void process(Map map) {}       // this allows you to change Map implementation
    }Suppose you use a HashMap for map2 to start with. But at some point in the future you would like to ensure your map is sorted. By specifying map2 to be a Map, you can change the implementation without having to modify each method call by simplying changing the initiliastion to be:
    Map map2 = new TreeMap();Hope some of this helps :) Cheers, Neil

  • Overwriting a method of a super class in the subclass ???

    Hi,
    can somebody tell me whether it's possible to add a new implementation of a method in the sub class which is inherited from a super class?
    I want to model my program in that way:
    1. I define a super class with some implemented methods.
    2. This class should be inherited in a sub class. One method should be used as it was implemented in the super class but another method should be overwritten in the subclass.
    I know this concept from Java but I couldn't find a way how to do it in ABAP
    Many thanks for any help!
    Best regards,
    Birgit

    hi,
    yeas you can do it,
    Subclass can re-implement  the inherited public and protected methods from superclass.Class C1 contains method METH1(public) and METH2(protected), both of which are modified and re-implemented in  its subclass C2.also you can have ur own methods in subclass.Objects are created out of both classes and the method METH1 for both objects are called.
    Output of the program demonstrates different behaviour for method METH1 of class C1 and C2.
    This demonstrates the theme.
    REPORT YSUBDEL.
    CLASS C1 DEFINITION.
      PUBLIC SECTION.
       METHODS : METH1.
      PROTECTED SECTION.
       METHODS METH2.
      ENDCLASS.
    CLASS C1 IMPLEMENTATION .
      METHOD : METH1.
       WRITE:/5 'I am meth1 in class C1'.
       CALL METHOD METH2.
      ENDMETHOD.
      METHOD : METH2.
       WRITE:/5 ' I am meth2 in class C1 '.
      ENDMETHOD.
    ENDCLASS.
    CLASS C2 DEFINITION INHERITING FROM C1.
    PUBLIC SECTION.
      METHODS : METH1 redefinition,
      meth3.
    PROTECTED SECTION.
      METHODS : METH2 redefinition.
    ENDCLASS.
    CLASS C2 IMPLEMENTATION.
    METHOD METH1.
       WRITE:/5 'I am meth1 in class C2'.
       call method meth2.
    endmethod.
      METHOD : METH2.
      WRITE:/5 ' I am meth2 in class C2 '.
    ENDMETHOD.
    METHOD : METH3.
      WRITE:/5 ' I am own method of class C2'.
    ENDMETHOD.
    endclass.
    START-OF-SELECTION.
      DATA : OREF1 TYPE REF TO C1 ,
             OREF2 TYPE REF TO C2.
      CREATE OBJECT :  OREF1 , OREF2.
      CALL METHOD : OREF1->METH1 ,
                    OREF2->METH1.
    hope it helps,
    regards

Maybe you are looking for

  • Mountain Lion brings bugs and breaks Automator Services

    Just love this Automator tool, been using it to make my Finder dance for a while now.  My fresh install (Erase/USB) of Mountain Lion seems to be reproducibly broken for adding Services, and also appears to have a bug for editing existing Services...

  • Variable Data in soap header?

    Hi, I'm trying to get a variable called sessionID inserted into my soap header for an outbound call. So my soap header would look something like this: <soapenv:Header> <SessionHeader > <ns1:SessionID>varSessionID</ns1:SessionID> </SessionHeader> </so

  • Show T and F boolean text simultaneously?

    I would like to show both True and False boolean text values simultaneously at different locations. Is there any way to do this? I want to use a toggle or rocker switch and be able to see both values at all times. In an old post Ben and TiTou showed

  • Interconnect IP address

    How would you find the interconnect IP address from any node within an Oracle 10g RAC configuration?

  • Unable to start ldmd on Solaris 11 IO Domain

    Hi all, I have a T4-4 box running Solaris 11 as the control domain. I also have another IO domain within the box running Solaris, this is a brand new fresh install. I am trying to get the ldmd daemon running so I can export the virtual disk service b