Solved

why upcasting is dangerous

Posted on 1998-11-19
7
408 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
basic hardware to learn oop advanced design patterns 3 88
groupSum6 challenge 6 77
backtracking recursion  code 19 54
java 8 lambda expresssions exception handling 3 75
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

895 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

16 Experts available now in Live!

Get 1:1 Help Now