Solved

why upcasting is dangerous

Posted on 1998-11-19
7
405 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
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
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

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
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 learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

708 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now