Question about Object

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Jim Davis

    #1

    Question about Object

    If a method takes an Object parameter, can this parameter be type casted by
    any class?

    Example:
    public int compareTo(Objec t o) {
    Name n = (Name) o;
    }

    public int MultiplyPrint(O bject o) {
    String testString = (String) o;
    Int num = Integer.parseIn t(testString);
    int theResult = Math.pow(num,2) ;
    return theResult;
    }

    public Orange Apple2Orange(Ob ject o) {
    Apple apple = (Apple) o;
    // Convert to Orange
    Orange orange = (Orange) apple;
    return Orange;
    }

    Also, is it poor programming style to rely on type casting?

    TIA

    James Davis


  • Dan Nuttle

    #2
    Re: Question about Object

    You can TRY to cast an Object to another type, but of course, if the Object
    isn't an instance of that type, you'll get a ClassCastExcept ion. For
    instance, if the Object is actually a String, and you try to cast it as an
    OutputStream, it won't work.

    Whether or not it's poor programming to cast a type all depends on the
    situation. I don't think there's a single simple answer to that question.

    "Jim Davis" <mountain1228@y ahoo.com> wrote in message
    news:v6CdnQTXOu 1iw6_fRVn-3A@giganews.com ...[color=blue]
    > If a method takes an Object parameter, can this parameter be type casted[/color]
    by[color=blue]
    > any class?
    >
    > Example:
    > public int compareTo(Objec t o) {
    > Name n = (Name) o;
    > }
    >
    > public int MultiplyPrint(O bject o) {
    > String testString = (String) o;
    > Int num = Integer.parseIn t(testString);
    > int theResult = Math.pow(num,2) ;
    > return theResult;
    > }
    >
    > public Orange Apple2Orange(Ob ject o) {
    > Apple apple = (Apple) o;
    > // Convert to Orange
    > Orange orange = (Orange) apple;
    > return Orange;
    > }
    >
    > Also, is it poor programming style to rely on type casting?
    >
    > TIA
    >
    > James Davis
    >
    >[/color]


    Comment

    Working...