Solved

why upcasting is dangerous

Posted on 1998-11-19
7
413 Views
Last Modified: 2008-02-01
could you explain how upcasting using in java and why it is
dangerous to use it

thanks
0
Comment
Question by:anhben
  • 2
  • 2
  • 2
  • +1
7 Comments
 
LVL 16

Expert Comment

by:heyhey_
ID: 1227853
what do you mean be 'upcasting' ? but whatever it is, Java is a pretty safe language, so it can't be too dangerous ... :)
0
 
LVL 27

Accepted Solution

by:
BigRat earned 100 total points
ID: 1227854
Upcasting is a somewhat peculiar term but means converting an object declared as a base class of the class we actuall want. The best example in Java comes via the class loader. The loader can dynamically create classes from a file. The loader returns an object of type (class) Object. But you know that in file Fred.class the class is actually Fred. So you cast (or upcast) as follows :-
   
          Fred fred = (Fred)Class.getClassLoader().loadClass("Fred.class");

Here (Fred) is an upcast.

    The use of an upcast is only dangerous when, for example, the loadClass method returns something other than Fred; better said something not equal nor dervied from Fred. Then you get a Java Run-Time error when the casting takes place. (Not later thank God!).
    I hope that explains what you wanted to know.
0
 
LVL 5

Expert Comment

by:fontaine
ID: 1227855
I am sorry, but for me, what BigRat explains is downcasting.

From the Object-Orientation FAQ:

"Downcasting is the term used in C++ for casting a pointer or reference to a base class to a
derived class. "

Fred extends Object => (Fred)anObject is the action to cast a base class (Object) to
a derived class (Fred)  => downcasting.

Upcasting is exactly the opposite. Please consider the following piece of code:

http://jinx.umsl.edu/~subraman/cast0_ex1.html

It is a C++ example, but OO is OO. In short, if we have (B extends A) and  (C extends B)
we can cast the following ways:

        A a = new A(); // a is an instance of A
        B b = new B(); // b is an instance of B
        C c = new C(); // c is an instance of C

        B bb = (B)c; // we are upcasting C to B
        A aa = (A)c; // we are upcasting C to A
        C cc = (C)c; // we are downcasting B to C

The "problem" with upcasting is the following (we consider bb, which is an upcasted
version of c): the upcasted version has no more access to the functionalities (fields
and methods) that were provided by the original class. For example, if we have:

class A {
}

class B extends A {
}

class C extends B {

     public void print() {
         //...
     }
}

the upcasted version of c, which is now a B instance, has no more access to the print()
method.
0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 27

Expert Comment

by:BigRat
ID: 1227856
OK The Rat accepts what fontaine proposes, but I do not see how it is dangerous and furthermore it's automatic in Java.
0
 
LVL 5

Expert Comment

by:fontaine
ID: 1227857
I agree, there is nothing dangerous about this (and I have verified what was written about
upcasting/downcasting in several locations). The only thing one has to be carefull about is
to remember what was the original class exactly. For example, when you stock an object in a
Vector, it is implicitely upcasted (as the method to add in a Vector is addElement(Object o)).
To recover the original class, you have to remember what was exactly the class of the object
stored in the Vector, in order to downcast it and be able to access the fields and methods
that are making the class what it is. Remember indeed that the nextElement() method of a Vector enumeration only returns an Object class...

I have found an explanation in Bjarne Stroustrup's C++ book about the upcasting/downcasting
terminology. The classical way to draw an inheritance diagram is to draw one box per
class, the base class above the derived classes with an arrow from the derived class box
to the base class box. When one casts a derived class to a base class, we are going up
in the graph, hence the term "upcasting". When one casts a base class to a derived
class, we are going down in the graphs, hence the term "downcasting".
0
 
LVL 16

Expert Comment

by:heyhey_
ID: 1227858
>> The only thing one has to be carefull about is to remember what was the original class exactly.

but in Java you don't have to remember what was the original class of an object - every object has assotiated class and you can always get it using Object.getClass() method

java is real OO language - in Java you have Objects that livce thair own live - every object has a class - and variables - variable has classes too, and every variable can point to NULL, an Object of its class or some derived class.

so when you have this code
String st = "sample";
Object o = (Object)st;
String st2 = (String)o;

all the variables (st, st2, o) point to the same Object (of class String) but they have different variable types ...
so
Object o = (Object)st; // upcasting
is not dangerous at all - yopu stil have the same object, but you just use a different variable type that points to it


0
 
LVL 5

Expert Comment

by:msmolyak
ID: 1227859
Looks like the person asking the question already forgot about it...
0

Featured Post

Active Directory Webinar

We all know we need to protect and secure our privileges, but where to start? Join Experts Exchange and ManageEngine on Tuesday, April 11, 2017 10:00 AM PDT to learn how to track and secure privileged users in Active Directory.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
more than one jdk and one jre 1 50
eclipse buid path vs tomcat lib path 10 34
jsp login check 12 43
ejb on wildfly 5 30
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

829 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question