Casting Confusion

Hi,
I am studying for the SCJP exam, and there is something I've read that I can't figure out about Object Reference casting. I have read that to cast a Final Class to a Non Final class, the Final Class must "extend" the Non Final Class. Does this mean that the Final Class must be a subclass of the Non-Final class? How does this tie up with the fact that Final classes cannot be subclassed? I assume I a misunderstanding something somewhere! I would be grateful if someone could explain this to me.

I am studying for the SCJP exam, and there is
something I've read that I can't figure out about
Object Reference casting. I have read that to cast a
Final Class to a Non Final class, the Final Class must
"extend" the Non Final Class. Does this mean that the
Final Class must be a subclass of the Non-Final class?Yes.
How does this tie up with the fact that Final classes
cannot be subclassed? I assume I a misunderstanding
something somewhere! I would be grateful if someone
could explain this to me.Your Final class is extending a Non-Final class. That's fine.
If you tried to create a new NoGood class that extended Final class, you'd have a problem. That's what is prohibited by "final".
So it sounds like they want you to be able to do this:
// static type of LHS is NonFinalClass
// dynamic type of RHS is FinalClass
NonFinalClass foo = new FinalClass(); // OK, because a FinalClass IS-A NonFinalClass
// Now perform the cast.
FinalClass bar = (FinalClass)foo; // Cast is OK, because the dynamic type of foo is FinalClass%

Similar Messages

  • Object casting: confusion in ABAP Objects: Complete Reference book

    Hi,
    During Object Assignments using casting, is a Type Test carried out during the syntax check or at runtime?
    A.5.2.2 (page 1008) of 'ABAP Objects: The Complete Reference' says about Widening Cast: "...you must check at runtime...". However on the next page under A.5.3.2 it says of Widening Cast in Data References: "The syntax check precludes...".
    A.5.4 (page 1010) concerns Assignments between Object Reference Variables, but makes no mention of whether checks are carried out by a syntax check or at runtime.
    Also nowhere does it mention when Type Tests for Narrow casting takes place. Can anyone clear my confusion please? Unfortunatly I don't know enough about this stuff to test by writing some code.
    Thanks.

    William,
    Your questions can be answered by the following rule for object references, which I found in the book "ABAP Objects" by Horst Keller and Sascha Krüger:
    "... that the static type of the target variable must be equal to or more general than the dynamic type of the source variable."
    Here "static type" means the type with which an object reference variable is declared. "Dynamic type" is the type that the object reference variable has at runtime. The dynamic type of an object reference is always more special than its static type, otherwise a runtime error occurs.
    With this rule all your questions can be answered:
    1. The Narrowing Cast is always checked during the syntax check. Example:
    DATA o_ref1 TYPE REF TO object.
    DATA o_ref2 TYPE REF TO class_1.
    o_ref1 = o_ref2.  
    Here the reference o_ref2 has a dynamic type "class_1" or a subclass of it, which is narrower than its static type "class_1", which is narrower than the static type "object" of the reference o_ref1. Therefore, the syntax check says that the assignment is OK.
    2. The Widening Cast is always checked at runtime and requires an assignment using the operator ?=. If you use the operator = in the assignment, a syntax error occurs. Therefore the following  example produces a syntax error (try it yourself):
    DATA o_ref1 TYPE REF TO object.
    DATA o_ref2 TYPE REF TO class_1.
    o_ref2 = o_ref1.  
    The correction for this syntax error is:
    DATA o_ref1 TYPE REF TO object.
    DATA o_ref2 TYPE REF TO class_1.
    o_ref2 ?= o_ref1.
    Now the syntax check is satified, and the correctness of the widening cast is checked at runtime.
    Kind regards,
    Michael Kraemer
    Message was edited by: Michael Kraemer

  • Object Casting confusion

    Hello,
    I have two classes used in the insurance business. One is a Member, which is someone covered by insurance (eg. an Employee, Spouse, Dependent) and one is a Employee which is more specificly the person who actually has the insurance.
    I am reading records of a database and creating each record into a Member Object. My Employee object extends Member. I want to know put the business logic in my main method to determine which Members is an Employee, Dependent, or Spouse.
    I am explicitly casting down the hierarchy, which I thought was allowable. I even implemented Cloneable on the Member object to try to get it work. The compiler seems to be fine with it, but I keep getting a runtime error: "ClassCastException".
    I am trying to avoid extracting the information from Member and having to reassemble it into Employee by using inheritance. What am I missing?
    Thanks.
    public class Member implements Cloneable
         private Object ssn;
         private Object planNumber;
         private Object locationCode;
         private Object coverageType;
         private Object benefit;
         private Object hireDate;
         private Object retireDate;
         private Object lastName;
         private Object firstName;
         private Object middleInitial;
         private Object address;
         private Object city;
         private Object state;
         private Object zip;
         private Object dob;
         private Object doh;
         private Object relationship;
         private Object gender;
         private Object effectiveDate;
         private Object status;
         private Object order; //represents order in spreadsheet
         //setters
         public void setOrder(Object order) {this.order = order;}
         public void setSSN(Object ssn){this.ssn = ssn;}
         public void setPlanNumber(Object planNumber){this.planNumber =planNumber;}
         public void setLocationCode(Object locationCode){this.locationCode = locationCode;}
         public void setCoverageType(Object coverageType){this.coverageType=coverageType;}
         public void setBenefit(Object benefit){this.benefit=benefit;}
         public void setHireDate(Object hireDate){this.hireDate=hireDate;}
         public void setRetireDate(Object retireDate){this.retireDate = retireDate;}
         public void setLastName(Object lastName){this.lastName= lastName;}
         public void setFirstName(Object firstName){this.firstName=firstName;}
         public void setMiddleInitial (Object middleInitial){this.middleInitial=middleInitial;}
         public void setAddress(Object address){this.address = address;}
         public void setCity(Object city){this.city = city;}
         public void setState(Object state){this.state = state;}
         public void setZip(Object zip){this.zip=zip;}
         public void setDOB(Object dob){this.dob=dob;}
         public void setDOH(Object doh){this.doh=doh;}
         public void setGender(Object gender){this.gender=gender;}
         public void setEffectiveDate(Object effectiveDate){this.effectiveDate=effectiveDate;}
         public void setStatus(Object status){this.status=status;}
         public void setRelationship(Object relationship){this.relationship = relationship;}
         //getters
         public Object getSSN(){return this.ssn;}
         public Object getPlanNumber(){return this.planNumber;}
         public Object getLocationCode(){return this.locationCode;}
         public Object getCoverageType(){return this.coverageType;}
         public Object getBenefit(){return this.benefit;}
         public Object getHireDate(){return this.hireDate;}
         public Object getRetireDate(){return this.retireDate;}
         public Object getLastName(){return this.lastName;}
         public Object getFirstName(){return this.firstName;}
         public Object getMiddleInitial(){return this.middleInitial;}
         public Object getAddress(){return this.address;}
         public Object getCity(){return this.city;}
         public Object getState(){return this.state;}
         public Object getZip(){return this.zip;}
         public Object getDOB(){return this.dob;}
         public Object getDOH(){return this.doh;}
         public Object getGender(){return this.gender;}
         public Object getEffectiveDate(){return this.effectiveDate;}
         public Object getStatus(){return this.status;}
         public Object getOrder() {return order;}
         public Object getRelationship(){return relationship;}
    }//end class
    import java.util.*;
    public class Employee extends Member
         Employee()
         private Spouse spouse;
         private Dependent dependent;
         private ArrayList dependents;
         private static int numberOfDependents;
         public void setSpouse(Spouse spouse){this.spouse = spouse;}
         public Spouse getSpouse(){return this.spouse;}
         public Dependent getDependent(int n)
              dependent = (Dependent)dependents.get(n);
              return dependent;
         public void setDependent(Dependent dependent)
              ++numberOfDependents;
              this.dependent = dependent;
              this.dependents.add(dependent);
         public ArrayList getDependents()
              return dependents;
         public void setDependents(ArrayList dependents)
              this.dependents = dependents;
         public int getNumberOfDependents()
              return numberOfDependents;
    }//end class
    import java.util.*;
    //Employee objects can be selfstanding Employee(String SSN)
    //The Spouse and Dependent objects - e.g. Spouse(String SSN, e)
    public class InsuranceObjectDriver
    //     ****************** START MAIN **********************************     
         public static void main(String[] args)
              //Open connection and query table
              DatabaseObjects db = new DatabaseObjects("LIBRARY", "", "");     
              db.queryDb("Table1");
              ArrayList memberList = db.getAllRecords();
              Member member;
                   member = (Member)memberList.get(0);
                   if (member.getRelationship().equals("E"))
                        Employee e =(Employee) member;
                   }

    >
    I see nothing wrong with the casting, since Employee
    is a Member.
    My only assumption is that the actual instance of
    "member" is not an Employee...so check your
    getRelationship().equals("E") condition...it may give
    you true, where it should have been false.This is why I'm casting it explicity to a Employee
    For design-wise, I see Employee, Spouse, and
    Dependent are more of a Member role..and not a
    "Member" superclass. I don't understand what you are trying to tell me here. Member is the superclass. Employee, Spouse, and Dependent are subclasses of the Member, which is one of the problems. I have to explicity cast down the hierarchy.
    Plus, what's with all the
    "Object" in the Member class? I never seen anyone
    did this before.
    I understand that by defining the Member attributes
    as Object, you can
    set the underlying type to anything in the
    future...without having to change the code...but i
    think this is a bad idea (just my thought).I like it. It dummy proofs things a bit. The input files are often sloppy and bad, plus I really don't care to maipulate most of these fields, I just need to make sure they populate the objects.
    E.g. I build a quick and dirty application for non-techies, who don't pay attention to data types much (in my many experiences). I don't want the program to bomb out on Date of Hire (doh) because it was brought in through the JDBC connection as an Object and not a Date.
    Data is brought into the application from the resultset via a getObject(n) call. Why change it? I guess I could use wrapper classes for them but I can't see why right now, but will consider this when I figure out the casting issue.

  • 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

  • Doubts on casting concepts in TAW12 part 1

    Can someone help me clarify a little confusion on Casting in materials provided by SAP Education on TAW12 part 1.
    I attended ILT and my instructor emphasized that: "wherever in this material we read 'Up-cast' or 'Down-cast', we should consider this as an error because what they meant to say is exactly the opposite".
    This has now left me confused especially after revising.
    Can someone please share some light on these terminologies and concept? especially in relation to materials provided on TAW12 ABAP Workbench Concept Part 1 (2013 SAP AG. All rights reserved)
    I have not been able to find much materials online for this section of the book and for many others.
    Any help would be greatly appreciated.
    Vince

    Hi Vince,
                   First thing, STOP worrying about the SAP material whether the contain is right/wrong.
                  Now, what I understand is that the instructor tried to explain the concepts in a easy way to remember but has that seems to have messed up your basics on up-cast & down-cast.
    I have looked in my sap material ( but its 2005 SAP AG reserved ).  The definition are fine.
    Anyways I'll try to explain in my style:
    Narrow casting( up-casting ):- Assigning of a subclass instance to a reference variable of type " reference to super class ". Here we navigate from a more detailed view to one with less details.
    Widening Cast( down-cast ):-  Assigning a super class to a sub class. From a less detailed view to more detailed view.
                             SUPER CLASS( vehicle ) less details
                                       |
                                       |
                                       |
                                SUB CLASS ( car, truck, bus, bike ) more details
    PS:- Try to understand the meaning from the example and then go back to the definition in the material.

  • Client code cast error:EJB returning data in Collection of Objects

    Still trying to understand this EJB stuff.....
    My BMP EJB returns data to the client in a collection of objects;
      // Home interface (CountryHome) nothing unusual here
      public Collection findAllCountries()
      //Remote interface (Country) nothing unusual here
      public CountryModel getDetails()The data object is a serialised object;
      // data object - nothing strange here
      public class CountryModel implements Serializable {
        private int countryId;
        private String countryName;
        public CountryModel () {......etc etc
        public CountryModel getDetails()  {.......etc etc
        public String toString() { ...etcWhen I try and get at the data from the collection in the client code, calling getDetails() in CountryModel causes a cast exception. How can I get at the data?
      Collection a = home.findAllCountries();
      Iterator i = a.iterator();
      while (i.hasNext()) {
        Object obj = i.next();
        Country country = (Country)
             PortableRemoteObject.narrow(obj, Country.class);
        // this fails with class cast exception.....
        System.out.println(country.getDetails());And to add to the confusion, why does calling the remote interface's getPrimaryKey() method in the client code invoke the toString() method in the CountryModel class and work?
      while (i.hasNext()) {
        Object obj = i.next();
        Country country = (Country)
             PortableRemoteObject.narrow(obj, Country.class);
        // have no idea why this works.....but it does.....
        System.out.println(country.getPrimaryKey());Thanks, lebo

    hi,
    you are getting a collection of serializable objects and not remote objects. the narow method has to be applied only for remote objects (actually it is the stub that will be received on the client side).
    so you modify your code as,
    Collection a = home.findAllCountries(); Iterator i = a.iterator(); while (i.hasNext()) {    Object obj = i.next();    Country country = (Country)obj;
    this will definitely solve the problem.
    regards
    srini

  • Usage of widening cast in abap oops

    hi experts,
    I understood the widening cast concept. i want to know in what scenarios, the usage of widening cast makes sense. does the widening improve performance of the program? is there any scenario where we MUST use the widening cast in the logic? i want to understand how do we justify the usage of widening cast.
    please do not give me links explaining widening case. I know what widening cast is, but want to understand the need for it and how it helps in programing.
    thanks

    As for the thread's question: you use it when you have a subclass instance being pointed at by a superclass reference, and you need to access subclass specific components.
    Adding about widening / down cast:
    I repeat: you don't have choice.
    You actually do. Check the following example. BAPIRET2_T is a table type for BAPIRET2.
    You can call the method YOU know the actual referenced object of a subclass supports dynamically, like this:
    * Using downcasting
    DATA lo_tabledescr TYPE REF TO cl_abap_tabledescr.
    DATA lo_structdescr TYPE REF TO cl_abap_structdescr.
    DATA lv_linetypename  TYPE string.
    TRY.
        lo_tabledescr   ?= cl_abap_typedescr=>describe_by_name( 'BAPIRET2_T' ).
        lo_structdescr  ?= lo_tabledescr->get_table_line_type( ).
      CATCH cx_sy_move_cast_error.
        MESSAGE 'Error in downcast!' TYPE 'A'.
    ENDTRY.
    lv_linetypename = lo_structdescr->get_relative_name( ).
    WRITE: /, lv_linetypename.
    * Alternative way using dynamic calling
    DATA lo_typedescr_tab TYPE REF TO cl_abap_typedescr.
    DATA lo_typedescr_str TYPE REF TO cl_abap_typedescr.
    lo_typedescr_tab   = cl_abap_typedescr=>describe_by_name( 'BAPIRET2_T' ).
    TRY.
        CALL METHOD lo_typedescr_tab->('GET_TABLE_LINE_TYPE')
          RECEIVING
            p_descr_ref = lo_typedescr_str.
      CATCH cx_sy_dyn_call_error.
        MESSAGE 'Error in dynamic call!' TYPE 'A'.
    ENDTRY.
    lv_linetypename = lo_typedescr_str->get_relative_name( ).
    WRITE: /, lv_linetypename, '...again'.
    Note that in either approach, you should catch the relevant exception(s) that may occur, unless you are certain about the object's actual subclass.
    Edited by: Alejandro Bindi on Mar 31, 2010 5:47 PM
    As you can see I got confused by the narrowing / widening terms as well. I also found out the terms upcast / downcast to be much easier to understand.

  • Class cast exception using Finder method

    Hello. I'm new to J2EE. I have set up one entity bean but am having trouble
    with my current one.
    Basically, I have two finder methods:
    public ShareHistory findByPrimaryKey(Integer historyId)
            throws FinderException, RemoteException;
        public Collection findByShare(String shareId)
             throws FinderException, RemoteException; findByPrimaryKey works fine, but findByShare causes a class cast exception in java.lang.String.
    The stack trace in the server logs shows that it is my ejbActivate method in my entity bean causing the problem:
    public void ejbActivate() {
          //String numberString = (String) context.getPrimaryKey();
          //historyId = new Integer(numberString);
        historyId = (Integer) context.getPrimaryKey();
        }The stack trace from my client shows that the class cast exception occurs
    in the client at the System.out.println("shareid" + ": " + sh.getShareId());
    line:
    Collection c = sharesHistoryHome.findByShare("DCAN");
                     Iterator i = c.iterator();
                          while (i.hasNext()) {
                         ShareHistory sh = (ShareHistory) i.next();
                    System.out.println("shareid" + ": " + sh.getShareId());
                    System.out.println("value" + ": " + sh.getValue());
                     System.out.println("time" + ": " + sh.getTime());
                     System.out.println("date" + ": " + sh.getDate());
                     }//whileAs you can see I tried casting to a string in ejbactivate, but that simply causes an Integer class cast exception during findByprimaryKey instead. How do I allow both Integer and String objects to be used?
    Also I am a bit confused as to why the String passed to findByShare(String) is being used in context.getPrimaryKey() in the first place (if that is actually what's happening).

    Oops my FindByShare method was returning a collection of shareId's (strings) instead of a collection of Integer primary keys, which would explain the class cast exception.

  • 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

  • Socket Programing in J2ME - Confused with Sun Sample Code

    Hai Everybody,
    I have confused with sample code provided by Sun Inc , for the demo of socket programming in J2ME. I found the code in the API specification of J2ME. The code look like :-
    // Create the server listening socket for port 1234
    ServerSocketConnection scn =(ServerSocketConnection) Connector.open("socket://:1234");
    where Connector.open() method return an interface Connection which is the base interface of ServerSocketConnection. I have confused with this line , is it is possible to cast base class object to the derived class object?
    Plese help me in this regards
    Thanks in advance
    Sulfikkar

    There is nothing to be confused about. The Connector factory creates an implementation of one of the extentions of the Connection interface and returns it.
    For a serversocket "socket://<port>" it will return an implementation of the ServerSocketConnection interface. You don't need to know what the implementation looks like. You'll only need to cast the Connection to a ServerSocketConnection .

  • Dynamic class casting during runtime

    I'm reading parameters for my application from the configuration file. Then in the code I should dynamically during the runtime make class cast:
    (instead of having String in the code, I should cast the object to the class that was
    defined in the configuration file.)
    String tmp = (String) object;
    Could somebody provide an example how can I do this? I have understood I could use reflection API for this problem.

    I am not sure that I understand what you are asking correctly, but it might be something that bothered me some time ago.
    My problem was that I wrote names of Classes (as Stings) into a file, and later wanted to be able to initialize a specific object of the class based on String names that were read from that file.(sorry if this is confusing).
    I was programing a Chess simulator. All figures were subclasses of the class Figure, and were named Peon, Queen...)
    I wanted to make a new Peon object, for every "Peon" String that was read from the file, and to make an new Queen object for every "Queen" in the file and so on.
    I used something like this:
    String objectName = in.readUTF(); //or some other way to get a String
    Figure f = (Figure) Class.forName(objectName).newInstance(); Class.forName(String name) returns a object of class Class that represents all objects of type name.
    And invoking .newInstance() gives you a new object of the class that is being represented by the object of class Class that you invoked .newInstance() on.
    Sorry - migth be confusing again but i think it is correct.
    This call to .newInstance() calls the default no-argument constructor...
    There is no way to call a argument containing constructor with .newInstance()

  • Pro9000 Prints with Heavy Blue Cast

    Hello all!
    I have several Canon Pro9000 and Pro9000 Mark II printers. The Pro9000 Mark II printers are doing great. However, the Pro9000 printer is printing photos with a heavy blue cast to them. The blue is so heavy and so bad that any photo printed with it is destroyed.
    I have tried printing both from Photoshop and from other programs, including straight from Window's photo viewer. When printing from Photoshop, I have tried both letting Photoshop manage colors and the printer manage colors. When Photoshop is managing colors, I've turn color management off for the printer (set it to None). I've made sure I have the proper paper selected, etc. It does not matter what I do, the Pro9000 still prints with a heavy blue cast.
    I've tried switching from Auto to Manual in an attempt to reduce the blue. But even if I have the first slider (labeled Cyan) slid all the way to the red side and the third slider (labeled Yellow) slid all the way over to yellow, I am still getting a heavy blue, but now the images are too red and too yellow, etc.
    What can I do to figure out what is going on with this printer? It used to print properly, so I am not sure what changed. Any help would be much appreciated.
    Thank you.
    PS - I am running Windows 8.1, 64-bit.
    Solved!
    Go to Solution.

    I don't have any 9500's. I have two Pro9000's and four Pro9000 Mark II's. The Mark II's all print fine from the same computer(s). Both of the Pro9000's (non-Mark II) are printing with the heavy blue tint.
    The monitor being right should not be an issue here. After all, what I see is what I get with the Pro9000 Mark II's.
    I've tried both letting Photoshop handle all the color profiling and letting the printer do it. I get the same blue tinting. Just FYI - I cannot always use Photoshop to print. I do event photos where I am using a Hot Folder for printing. In cases like this, Photoshop is not even running. That's when I need the printer to handle color profiling (the hot folder software I currently use has not control over this). Again, this works fine with the Pro9000 Mark II's.
    I've played with numerous settings and nothing is removing the blue tinting. I thought it might be the print heads, but the check nozzle pattern looks like it is printing just fine. This is why I am confused.

  • Form to compare two fields ... cast needed?

    Hi all gurus,
    I'm rebuilding a report that performs a lot of checks by comparing fields of two different structures.
    Basically, the check has a structure that is repeated over and over in many check: it looks like this:
    IF srm_items-{field1} NE r3_services-{field2}.            
       t_temp-prezzi_errati = icon_red_light.
       t_temp-error_code    = '{errorcode}'.
       IF counter_s = 0.
          PERFORM add_son_in_t_temp USING srm_items e_backend w_obj-posting_date w_obj-changed_at.
       ELSE.
          PERFORM add_additional_error_temp USING srm_items 0.
       ENDIF.
       counter_s = counter_s + 1.
       fl_errore_s = 'X'.
    I was thinking to create a form, say 'check_son', that takes as USING parameter , and . My doubt is about types ad casts; in a check, could be a text string, in another a number, in another again a guid, and so on. Always simple field (no structures or complex field by now), but for what that concerns my FORM:
    FORM check_son USING compare1
                                          compare2
                                          errorcode.
    how should I declare the form in order to have the check working? I mean, I'd like that compare1 and compare2 get the same TYPE of the parameter I pass.. Is there a way? Or implicitly the params are converted into text (this should not work for me)?
    Thanks in advance

    >
    Matteo Montalto wrote:
    > I don't know macros
    Hi, Matteo
    Test the following Sample Code it will help you to understand the working of Macros.
    DEFINE check_son.
      if &1 NE &2. " If Field1 Not Equal Field2
        &3 = 'NE'. " In This Variable it will Return Error Code NE for Not Equal and EQ for Equal
      else.
        &3 = 'EQ'.
      endif.
    END-OF-DEFINITION.
    DEFINE write_message.
      if &1 = 'EQ'.
        write: 'Two Numbers are Equal', /.
      else.
        write: 'Two Numbers are Not Equal', /.
      endif.
    END-OF-DEFINITION.
    DATA: f1 TYPE i,
          f2 TYPE i,
          error_code(2).
    f1 = 10. f2 = 15.
    check_son f1 f2 error_code.
    write_message error_code.
    f1 = 10. f2 = 10.
    check_son f1 f2 error_code.
    write_message error_code.
    Please Reply if any Confusion,
    Best Regards,
    Faisal

  • Invalid casts - Object and Integer

    OK, I have got myself confused with casts. I have written this code, which I have [bold]SUBMITTED[bold] to University (so if you change it you are not helping me cheat...) . It doesn't compile and I am out of ideas why. The problem is the last method returnEvenNumbers(). Please could someone help me learn how this should be used by turning this into running code.
    * Filename: RandomNumberArray.java
    * Author: Steven Lane
    * Email: [email protected]
    * Created on 17 February 2002, 17:53
    * Course: KIT eLearning, MSc in IT, University of Liverpool, UK
    *         MSC-JV0020110-03
    * Purpose: This class creates an uncostrained array of length L passed as int on instantiation.
    *          The array is populated with (pseudo) random numbers.
    *          Methods contain a filter for even numbers, which is pushed onto a stack.
    * Version: 0.2
    //package com.thinkcorporation.week6;
    // ------------------- Import Packages -------------------
    import java.util.*;
    // ------------------- Class Heading -------------------
    public class RandomNumberArray extends java.lang.Object {
        // ------------------- Field Defintions -------------------
       private Stack stkEvenNumbers = new Stack();
        private int [] rndNoArray;
        //private int [] evenNoArray;
        private Integer evenNoArray[];
        // ------------------- Constructors -----------------------
        public RandomNumberArray(int length) {
            rndNoArray = new int [length];
            populateRndNoArray();
        //------------------- Methods -----------------------------
        private void populateRndNoArray() {
            Random rnd = new Random();
            for(int counter = 0; counter < rndNoArray.length; counter++) {
                rndNoArray[counter] = rnd.nextInt();
        public void evenNumberFilter() {
            for(int counter = 0; counter < rndNoArray.length; counter++) {
                if (rndNoArray[counter]%2 == 0)
                    stkEvenNumbers.push(new Integer(rndNoArray[counter]));
        public int [] returnEvenNumbers() {
            if (!stkEvenNumbers.empty()) {
                evenNoArray = new Integer [stkEvenNumbers.size()];
                evenNoArray = (Integer)stkEvenNumbers.toArray();
            return evenNoArray;
    }You help is much appreciated.

    The root of the problem is a difference between primitive types and objects. The Stack.toArray() method returns an array of Objects (Object[]), which you can cast to an array of Integer objects (Integer[]):
    evenNoArray = (Integer[])stkEvenNumbers.toArray();However, your return type for that method is int[] - a primitive types, not objects. Meaning that you either have to step through the array and build an array of ints (using Integer.intValue()), or you have to change the return type of your method.

  • Confused: Returning Simple User Defined Type (non-built-in)

    Hi, hope you can straighten out a confused newbie! This is probably laughingly simple if you know how...
    I just want my weblogic workshop web service to return an ordinary record-style object to my static client. I'm not sure what to do, I've already tried a few approaches...
    If I use two services deployed on Weblogic Server everything works great. Weblogic server must handle the seriali/deseriali - zation for you.
    So I tried to use the java proxy downloaded from the test page, but it doesn't contain all the classes needed.
    I read the Weblogic help files which said to use autotype, which compiles but gives class cast exceptions running. I tried both automatic and manual with same error. Trying to import to Workshop gave me a "no handler defined error".
    And I bought a book from Amazon about J2EE and Weblogic but it does not include a section on user defined types!
    Am I supposed to use XMLBeans or something??? Please help!
    Regards, Ry.

    > but the requirement is not allowing me to do either with ref cursor or with
    returning clause. Because, in .Net development area , we are restricted for
    using Returning clause.
    The following is a Bad Idea (tm) where PL/SQL is used to "return data" to the caller, be that via PL/SQL record types or collection types..Net   ---[calls]-------> PL/SQL
    PL/SQL ---[calls]-------> SQL
    PL/SQL <--[data]--------- SQL
    PL/SQL [buffers] data
    .Net   <--[buffer data]-- PL/SQLWhy?
    Because PL/SQL is a poor choice for a buffer as the db cache buffer used by the SQL engine is a very advance and sophisticated cache and core to the Oracle RDBMS.
    Ain't no way you can do that better in PL/SQL than SQL.
    What is the typical client-server approach in Oracle?.Net   ---[calls]-------> PL/SQL
    PL/SQL [constructs ref cursor]
    .Net   <--[ref cursor]-- PL/SQL
    .Net   --[fetches]----> SQL [using ref cursor]A ref cursor is a pointer the "compiled and executable SQL program" in Oracle that PL/SQL constructed for .Net in this case. Each FETCH call using the ref cursor pointer, executes the cursor "program" and returns the next row (or set of rows when using bulk processing) to the client.

Maybe you are looking for