Instanceof operator question

Can you use instance of (successfully) on interfaces and abstract classes?
I am confused because if class A implements interface B (or extends abstract class B) it is a type of B but it is not an instance of B, since interfaces/abstract classes cannot be instantiated.

Sorry, the reason I ask is because on weekdays I have limited internet time so if I ask it here I can work on my projects and get the answer without taking time away from working on my project. Thanks for the answers.

Similar Messages

  • Is the 'instanceof' operator discouraged ?

    Hi,
    I have heard that the instanceof operator is not recommended and should be used only as a last resort. Can someone throw some light into it ? is there an alternative ?
    thanx and regards

    hi,
    thanx for the response.
    well, the BaseException and its subclasses belong to a different applicaiton, and my application calls this application thru remote interface.
    For each of the 5 sub-exceptions, we need to log a different message, and then propogate the same to our client.
    There is too much code repetetion-- My session bean has 10 methods, each of these catch the 5 sub-classes, log a message and throw a new exception.
    To avoid code repetetion, i ll catch the BaseException in each of the 10 methods of session bean, and then in the catch block, i ll call a method say -- handleExeption, which will identify the type of exception and take the action that were taken earlier by the multiple catch blocks.
    Now, I need to use the instanceof operator to identify the specific type of exception. Will it be recommended practice ?
    thanx and regards

  • Avoiding using instanceof operator

    I've heard that using the instanceof operator isn't such a great code technique, and since I'm in the design phase, I feel like I should be able to avoid this. Right now, part of my design requires use of the instanceof operator as well as casting.
    Let's say you have a common notifier interface and two abstract classes which extend from this interface:
    com.example.Notifier Interface:
    public void doNotify(Notification notif, List notifiables);
    public boolean canSend(Notification notif, Notifiable person);
    com.example.SerialNotifier (abstract)
    public void doNotify(Notification notif, List people)
        for (Iterator itList = people.iterator(); itList.hasNext();)
             Notifiable person = (Notifiable)itList.next();
             doNotify(person, notif);
    public abstract doNotify(Notification notif, Notifiable person);
    com.example.MulticastNotifier (abstract)
    public abstract void doNotify(Notification notif, List notifiables);MulticastNotifier purposefully doesn't define a way to send a message to a single person, so that developers don't implement a non-multicast solution for a multicast protocol.
    Here's the part that seems to require an "instanceof" clause. Now let's say you have a list of Notifiers. The list of notifiers is mixed, containing both Serial and Multicast Notifiers. Before you send out the notification, you need to filter the list (because for example, someone doesn't want to be notified at all):
        for (Iterator itNotifiers = notifiers.iterator(); itNotifiers.hasNext();)
             Notifier notifier= (Notifier)itNotifiers.next();
             List buildPeopleList = new ArrayList();
             for (Iterator itPeople = people.iterator(); itPeople.hasNext())
                   Notifiable person= (Notifiable)itPeople.next();
                   if (notifier.canSend(person, notification))
                           if (notifier instanceof MulticastNotifier)
                                  buildPeopleList.add(person);
                           } else
                                   SerialNotifier serialNotif = (SerialNotifier)notifier;
                                   serialNotif.doNotify(notification, person);
             if (notifier instanceof MulticastNotifier)
                      notifier.doNotify(notification, buildPeopleList)
        }Is this bad design? Another option is to just iterate through the list essentially twice, but this is of course, less efficient for the serial notifier case:
        for (Iterator itNotifiers = notifiers.iterator(); itNotifiers.hasNext();)
             Notifier notifier= (Notifier)itNotifiers.next();
             List buildPeopleList = new ArrayList();
             for (Iterator itPeople = people.iterator(); itPeople.hasNext())
                   Notifiable person= (Notifiable)itPeople.next();
                   if (notifier.canSend(person, notification))
                           buildPeopleList.add(person);
             notifier.doNotify(notification, buildPeopleList);
        }Any suggestions?

    I'm not sure what you mean. I moved a loop from your
    code to a different class. AFAICT, it's a
    one-for-one. My solution has the same number of
    iterations as yours.Yeah, your code is actually missing a loop, because, as I explained earlier, the design supports filtering at both a parent notifier and a child notifier. To filter, it needs to loop through the list of people
    So, your code actually will look like: (forgive me, doing code in a textarea is kinda a pain)
    public void ParentNotifier implements Notifier
    // member var for simplicity
    protected Filter myFilter = new ExampleFilter();
    protected List notifiers = // list of notifiers
    public void doNotify(Notification n, List people)
      List intermediateList= new ArrayList();
      for (Iterator itPeople = people.iterator(); itPeople.hasNext();)
            Notifiable person = (Notifiable); itPeople.next()
            if (myFilter.canSend(n, person) // parent's filter
                 intermediateList.add(person);
       for (Iterator itNotifiers = notifiers.iterator(); itNotifiers.hasNext();)
                    Notifier notif = (Notifier)itNotifiers.next();
                    notif.doNotify(n, intermediateList); // 2nd loop is in here where additional filtering takes place
    }If you assume a serial notifier, you don't need this additional iteration:
    public void ParentNotifier implements Notifier
    // member var for simplicity
    protected Filter myFilter = new ExampleFilter();
    protected List notifiers = // list of notifiers
    public void doNotify(Notification n, List people)
      for (Iterator itPeople = people.iterator(); itPeople.hasNext();)
            Notifiable person = (Notifiable); itPeople.next()
            if (myFilter.canSend(n, person) // parent's filter
                 for (Iterator itNotifiers = notifiers.iterator(); itNotifiers.hasNext();)
                         Notifier notif = (Notifier)itNotifiers.next();
                         // PROBLEM HERE: assumes serial notifier
                         notif.doNotify(n, person); // child will do own filtering
    }Edit: Corrected logic error in code

  • Java InstanceOf operator

    I am writing a program that runs on a simulated network, that exposes my data to potential corruption. So, if I send an object across the network and some of the bytes in that object get corrupted will the instanceof operator still recognize that object as a member of a particular class even though some of the data is corrupted, or does it depend on which actual bytes are corrupted?

    When an object is serialized part of what's sent is the name of the class, and that's all that determines what class of object it will attempt to reconstruct..
    If you're using an unreliable connection stream then you should probably add a CRC check of some kind. Most of the channels you migh use have that built in.

  • Instanceof operator, please help!

    I am reading the codes written by others. I am confused on instanceof operator here.
    (A instanceof B) where A and B are interfaces. I found a definition in a book such that the
    instanceof operator returns true or false based on whether the object is an instance of the named
    class or any of that class's subclass. However, I didn't find the relationship between A and B is
    established in the codes. In this case, I wonder if instanceof operator can still be used because I am thinking that it will always evaluate to be false.
    Thank you for your help!
    Cathy

    The instanceof operator can always be used - a return value of false is still a valid return value!
    However, when it comes to interfaces it is possible for a class to implement both interfaces even though there may be no direct relationship between those interfaces.
    Have a look at this:
    public interface MyInterface
    public interface YourInterface
    public class MyClass implements MyInterface, YourInterface
    }There is no relationship between the two interfaces but I can still do this:
    public void check(MyInterface myObj)
      if(obj instanceof YourInterface)
        YourInterface yourObj = (YourInterface)myObj;
        System.out.println("Woo hoo - an instance of MyInterface that's also an instance of YourInterface!");
    }Essentially the instanceof operator is asking if the value passed can be cast to something else for the method to use it more specifically.
    There could be classes other than MyClass that implement both interfaces, particularly if a system is designed to be flexible.
    I hope this makes sense!

  • Save As operation Question

    Scenario - I have a web application that generates Excel documents that can be downloaded or opened directly. The web pages are a mixture of both ASP.NET and Classic ASP so the Excel file is actually generated as an HTML table. When a Save or Save As operation
    is done when the .xls file is downloaded a specified file name passed from the web page is used in the save operation. When you open the Excel file after saving Excel displays "The file you are trying to open "filename.xls" is in a different
    format than specified by the file extension...Do you want to open the file now?" informing me that the file is not a true xls file. When you continue with the opening the file it opens normally with no issues.
    Question or Possible issue: Taking one of these files after it has been saved to a location on the computer outside of the download folder, and perform a Save As operation to change the format to a true .xls file the theExisting File Name is not displayed in
    the File Name field. The Save as type defaults to Web Page which is understandable due to how the file is generated.
    I've tried this with actual Excel spreadsheets and the File Name field on the Save As operation is populated with the current name of the file and keeps it even if you change the Save as type.
    Main Question: Is there a setting somewhere in Excel to prevent the loss of the File Name?

    Hi,
    According to your description, the "The file you are trying to open "filename.xls" alert is from a feature called Extension Hardening, and you can find more information about it here. 
    http://blogs.msdn.com/b/vsofficedeveloper/archive/2008/03/11/excel-2007-extension-warning.aspx
    As you said and tested, Excel will retain the current file name in file name field when we save/save as the file. It's a default behavior. I suppose that the issue may be caused by the Excel that generated by web application.
    I recommend we try the 3 workarounds:
    1. Modify the ASP.NET program and make the file change to new excel format when generated
    Please see the thread:
    http://stackoverflow.com/questions/940045/how-to-suppress-the-file-corrupt-warning-at-excel-download
    2. Use "Office Migration Planning Manager" to convert the XLS to XLSX format.
    The toolkit also contains the Office File Converter (OFC), which enables bulk document conversions from binary to OpenXML formats. 
    Overview on Technet
    Download Link
    3. Use a macro to convert batch of XLS file to XLSX file and retain the file name.
    Sample code:
    Sub ProcessFiles()
    Dim Filename, Pathname, saveFileName As String
    Dim wb As Workbook
    Pathname = "C:\Users\myfolder1\Desktop\myfolder\Macro\"
    Filename = Dir(Pathname & "*.xls")
    Do While Filename <> ""
    Set wb = Workbooks.Open(Pathname & Filename)
    saveFilename = Replace(Filename, ".xlsx", ".xls")
    wb.SaveAs Filename:=Pathname & saveFilename, _
    FileFormat:=xlExcel8, Password:="", WriteResPassword:="", _
    ReadOnlyRecommended:=False, CreateBackup:=False
    wb.Close SaveChanges:=False
    Filename = Dir()
    Loop
    End Sub
    Regards,
    George Zhao
    TechNet Community Support
    It's recommended to download and install
    Configuration Analyzer Tool (OffCAT), which is developed by Microsoft Support teams. Once the tool is installed, you can run it at any time to scan for hundreds of known issues in Office
    programs.

  • The Shift operator Question

    Dear sir/madam
    I having question for the shift operator.
    What different between >>> and >> ?
    I have refer to sun tutorial, it state >>> is unsign, what does it mean?
    and last is
    if integer is 13
    what anwer for 13>>8
    is it move for 8 right by position? pls told me in detail
    is it answer same with the 13>>>8 ?
    Thanks for ur solutions

    You can play with the following for a while.
    final public class BinaryViewer{
      final static char[] coeffs = new char[]{(char)0x30,(char)0x31};
    public static String toBinary(int n) {
      char[] binary = new char[32];
      for(int j=0;j<binary.length;j++) binary[j]=(char)0x30;
      int charPointer = binary.length -1;
      if(n==0) return "0";
      while (n!=0){
          binary[charPointer--] = coeffs[n&1];
          n >>>= 1;
    return new String(binary);
    public static void print(int n){
        System.out.print(BinaryViewer.toBinary(n));
        System.out.print("   ");
        System.out.println(String.valueOf(n));
    public static void main(String[] args) throws Exception{
       int n=Integer.MIN_VALUE;//Integer.parseInt(args[0]);
       int m=Integer.MAX_VALUE;//Integer.parseInt(args[1]);
       BinaryViewer.print(n);
       BinaryViewer.print(n>>8);
       BinaryViewer.print(n>>>8);
       System.out.println();
       BinaryViewer.print(m);
       BinaryViewer.print(m>>8);
       BinaryViewer.print(m>>>8);
      System.out.println();
        n=1024;
        m=-1024;
       BinaryViewer.print(n);
       BinaryViewer.print(n>>8);
       BinaryViewer.print(n>>>8);
       System.out.println();
       BinaryViewer.print(m);
       BinaryViewer.print(m>>8);
       BinaryViewer.print(m>>>8);
      System.out.println();
       n=2048;
       m=-2048;
       BinaryViewer.print(n);
       BinaryViewer.print(n>>8);
       BinaryViewer.print(n>>>8);
       System.out.println();
       BinaryViewer.print(m);
       BinaryViewer.print(m>>8);
       BinaryViewer.print(m>>>8);
      System.out.println();
    }

  • Range Operator Question

    Hello all,
    I asked a question yesterday under the title of "Range
    Operator for first 2 letters of item" which was answered promptly and was much appreciated. I have since encountered another problem and would like another example if possible.
    How would I search for all folders under C:\ that start with "Commercial_Global_Trading" through the end of all folders that start with "C"? Can I use a Range Operator for this as well?
    Hopefully it makes sense what I'm asking!
    Thanks!

    Yes it is a bit confusing. Maybe an answer from my previous post will help clear up what I'm asking:
    Using range operators, we can get folders that start with A, B, and C by saying:
    get-childitem 'C:\Folder\[a-c]*'
    We can also get folders that start with Aa, Ab, and Ac by saying:
    get-childitem 'C:\Folder\A[a-c]*'
    What I'm wondering is, is there a way to get all folders in a range, beginning with a specific
    word and then continue through the rest of the range? For example:
    The folder C:\Folder contains the following 6 folders:
    Account
    Commercial
    Commodity
    Commodity_Product
    Conduct
    Finance
    How would I use range operators in get-childitem to return the folders that start with Commodity, and then continue on through the rest of the C's? So the output would be the folders Commodity, Commodity_Product, and Conduct. The folder "Commercial" would
    be excluded from the output. Is this possible using Range Operators and Get-ChildItem?

  • Conditional operator question?

    Hello,
    Quick question, are we not allowed to use the conditional operator this way... see code below:
    char volatile ProgString_[] = "\
    {Fan code} \
    12 <Limit11> [C1_ACM2]_[B1] _AND_ \
    bla bla \
    unsigned char UPC_SYSZ_EndOfTable(unsigned long i){ // Find the double '*' in string
    char volatile *u;
    u = &ProgString_[i];
    if(!(strncmp("*", u, 1))){
    i++;
    u = &ProgString_[i];
    if(!(strncmp("*", u, 1))){
    return TRUE;
    else {
    return FALSE;
    else
    return FALSE;
    void UPC_SYSZ_Parse(){
    unsigned char volatile iOCntr = 0;
    unsigned long volatile i;
    for(i=0; i<200; i++){
    (UPC_SYSZ_EndOfTable(i))?(break):(continue); //<<<<< Invalid expression ??
    I would of used the following compact line:
    (UPC_SYSZ_EndOfTable(i))?(break):(continue);    //<<<<< Invalid expression ??
    to periodically test the end of the string by fetching the "EndOfTable() function and evaluating if the double star is detected.
    If detected, I would break out of the for loop, if not then I would continue.
    Is it possible to do it this way?
    thanks for all help!
    r

    Think of it along the lines of each of the operands of the ternary operator must produce a value (which of course break and continue being statements cannot do).
    Based on your brief example here is what I would do
    for(i=0; i<200; i++){
    if (UPC_SYSZ_EndOfTable(i)) break;
    // doesn't make any sense to put more code down here anyway, so no real point to continue}

  • CWMS 1.5 Operational Questions

    Hello All:
    I am looking for some help with my new CWMS 1.5 system.  I have several problems listed below.  If the features aren't in the current release, I am interested if they might be planned for an upcoming release.
    1.  How do you delete a user or a mis-typed email address?
    2.  How do you delete the branding logo?  We uploaded a logo but can't find a way to set it back to default.
    3.  How do you restrict some people to WebEx with desktop sharing and others to just personal audio conference calls?  Looking for some sort of class of service capability.  Might want to also allow Mobile and other features by class as well. 
    4.  How do you generate a report of the Userids, pins, and host/moderator numbers assigned? 
    5.  How do you turn off email notifications?  We want to load a large list of users but when we do it sends everyone an email.  We are trying to stage the system and get ready for testing.
    6.  Is there a way to allow someone from our Service Desk to act as an operator on a call that would be able to mute a line?  Looking for some sort of BigBrother capability.  Should have full access to someones account and all active conference calls.
    7.  Is there a way to get a report of what numbers were dialed?  Looking to determine number of internal versus external callers.
    8.  Why is public access required for IOS functionality?  The IPAD or IPHONE can be on the company local network or connected with a VPN connection.  We don't have IRP installed but IOS should still work.

    Hello David,
    Let me answer some of your questions:
    1. You cannot delete a user profile. If you mis-typed an e-mail address, all you can do is DEACTIVATE the profile. The behavior is the same as in WebEx SaaS.
    2. At this time there is no supported way to delete the company logo using GUI. I am sure there is a way to remove it via CLI, but you would need TAC assistance for this.
    3. At this time, it is not possible to differentiate privilege levels on per user bases. Any changes to capabilities is done on per system basis.
    4. All the available reports are found in the Reports section. There is no such a report that you are looking for. Only available reports that come within Customize Your Report are:
    UserLicenseUtilizationReportForThisMonth.csv
    UserLicenseUtilizationReportForLastMonth.csv
    SystemDowntimeReport.csv
    NetworkBandwidthUtilizationReport.csv
    MeetingReport.csv
    FraudAttemptsReport.csv
    5. At this time, if you are importing users via CSV file, only if you mark the user as INACTIVE during the import (in a csv file under column ACTIVE you mark N for the user profile) the system won't send an e-mail. Once you mark the user as ACTIVE, the system will e-mail the end user.
    6. At this time, only host of the meeting can perform those actions within the WebEx Meeting Room.
    7. There is no such a report in CWMS.
    8. I cannot provide you an answer for this question as this is rooted in product design. Mobile devices require IRP server to be able to join meetings on CWMS.
    I hope any of these answers will help.
    -Dejan

  • WLS 11g License File Operational Question

    Hello,
    I understand there is no license file anymore with WLS11g download, however of course you need a license for usage of WLS11 in production.
    So I understand it is more a legal issue that you have to buy a license.
    My question is, what do you get if you buy a license for WLS?
    - A file that is technically not used?
    - A letter stating you have bought a license that can be used for a particular CPU?
    I wonder if you still get a file (which does not affect the functionality of WLS) do I have to take care to place in the right location for legal lissues?
    I am thinking of operational guidelines in bigger/big environments.
    - Is there a technical way to check/gurantee in large environmnet by talking to the WLS instances and retrieve the current licensing?
    I guess no one wants to risk running unlicensed instances.
    thanks for your input to this untypical question,
    B.

    If you contact support, there has been discussions going on of making available some type of auditing software to cover the cases that you mention for organizations that want to monitor their compliance and deployments on their own. I'm not sure the status of that effort.
    The license file is no longer even present in 11g at all.

  • LIKE OPERATOR QUESTION

    Hi All,
    Quite simply I don't really understand two things.
    1) How is the LIKE operator is working to return both columns.
    2) When to use the LIKE operator and when to use the relation operator.
    Thanks.
    (CODE)
    SELECT *
    FROM ( SELECT TO_DATE ('01/01/2009 12:01:01', 'DD/MM/YYYY HH24:MI:SS') aa,
    TO_DATE ('1-Jan-2009') bb FROM DUAL
    WHERE aa LIKE bb
    --returns both columns
    SELECT *
    FROM ( SELECT TO_DATE ('01/01/2009 12:01:01', 'DD/MM/YYYY HH24:MI:SS') aa,
    TO_DATE ('1-Jan-2009') bb FROM DUAL
    WHERE aa = bb
    --returns nothing
    (/CODE)

    Hi,
    DaveyB wrote:
    Hi All,
    Quite simply I don't really understand two things.
    1) How is the LIKE operator is working to return both columns.The WHERE clause (whether it contains LIKE or anything else) will only control the number of rows: every row will have the same numberr of columns.
    2) When to use the LIKE operator and when to use the relation operator.Use LIKE when you want to use "wildcards" (% or _).
    Use other operators (like =) when you don't have wildcards.
    (CODE)
    SELECT *
    FROM ( SELECT TO_DATE ('01/01/2009 12:01:01', 'DD/MM/YYYY HH24:MI:SS') aa,
    TO_DATE ('1-Jan-2009') bb FROM DUAL
    WHERE aa LIKE bb
    --returns both columns
    SELECT *
    FROM ( SELECT TO_DATE ('01/01/2009 12:01:01', 'DD/MM/YYYY HH24:MI:SS') aa,
    TO_DATE ('1-Jan-2009') bb FROM DUAL
    WHERE aa = bb
    --returns nothing
    (/CODE)It's great that you're trying to format your code! I wish everyione did that.
    Use square brackets (&#091; and &#093;) if you want to use &#091;CODE&#093; and &#091;/CODE&#093; tags.
    LIKE operates on strings. Don't use a DATE where a string is required. Do some experiments like the ones you tried just using strings, if you want to see how LIKE behaves.

  • Quick if operator question

    If a and b contain a number each, what should
    if(a>0&&b6=0)be?

    = --> assignment operator
    example:
    a = 0;
    a = a + 1
    // a now equals 1; it doesn't solve the algebraic equation or anything
    == --> comparison operator, returns boolean value
    example:
    if(a == 0)
    // do something
    Now you can correct it.
    theAmerican

  • Math Addition Operator Question

    Hi there,
    I'm trying to write a very simple math equation:
    var gal_width = 100;
    var m_box_pos = 2000;
    var total = (gal_width+m_box_pos);
    When I display this in a text element, the numbers are shown together rather than being added together
    (eg: 1002000)
    I get the feeling Edge is interpreting the + as a string operator rather than a math operator.
    Replacing the + with a - (as a test), the 2 numbers are being subtracted.
    Multiplying the numbers with the * operator also works as it should.
    I've tried many configerations, escaping the operator with no luck.
    Any ideas of how to get addition to work?
    Thanks

    Hi 29sketc.
    console.log( sym.$("text_111").text());
    // logs : 111
    console.log(typeof sym.$("text_111").text());
    // logs : string
    var number_222 = 222;
    console.log(typeof number_222);
    // logs : number
    console.log( sym.$("text_111").text() +number_222);
    // logs : 111222
    text() has produced a String so + is interpreted here as string concatenation.
    var number_111 = 111;
    console.log(typeof number_111);
    // logs : number
    console.log(number_111 +number_222);
    // logs : 333
    When you have two Number variables + is interpreted  as addition.
    Gil

  • Post Increment Operator Question

    I had written a small program to test the working of Post increment operator.
    public static void main(String[] args)
         int a = 4;
         a = a++;
         System.out.println ( a );
    I expected the output to be '5', but the output given is '4'.
    Can anyone tell me to how this works in Java ?

    There is a big difference between a++ and ++a.
    a++ means increment a AFTER you have performed the line.
    ++a mean increment a BEFORE you perform the line.
    class Test
    public static void main(String[] args)
    int a = 4;
    a = ++a; //returns a = 5
    // a = a++; //returns a = 4
    //a++; //returns a = 5
    //++a; //returns a = 5
    System.out.println ( a );
    }

Maybe you are looking for

  • SRM 7.0: Authorisation object? Aliases for services in java portal?

    Here's how we did in old SRM 5.0 system (the old and working scenaio): In SRM 5.0 we employed S_ICF object to determine, whether a particular user who has just logged in to a system via web using a particular alias - is authorised to use this service

  • How to add a field in a table control of the subscreen 6103 of tcode f-03

    hi abap gurus....i m new to abap and this is my first post ..i m hoping for a reply soon as it is urgent.... my requirement is to add a field PAYR-CHECF to a table control of the subscreen 6103 of tcode f-03

  • Sitemesh with e-commerce 5.0

    Hi, I am trying to use a decorator framework (Sitemesh) and it does not seem to work properly (or as intended) with SAP e-commerce 5 application. The reason I assume is that because the e-coomerce application uses sturts framework which does a forwar

  • Wrong Foreign Trade Data in Delivery

    Hi All, When creating Delivery Document with reference to PO ,Foreign Trade is wrongly copied at Item Level in the fields :"Export procedure" , "BusTransactType" & "Region of origin". The Data which is copied wrongly in delivery document from PO in t

  • Profit Center blocked error in depreciation run

    We are upgrading SAP system from 4.6 to 6.0. It was noticed that Profit Center blocked error is being captured in depreciation run test run in the upgraded version. In 4.6, this error is not being captured. Is this an enhancement in the upgraded vers