Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

What is downcasting in Java?

Posted on 2011-09-09
13
Medium Priority
?
615 Views
Last Modified: 2012-05-12
My textbook says "To access a specific method of the object, we must downcast to the correct type. (Of course, in this example we do not need the downcast, since we are simply invoking the toString method at line 9, and this can be done for any object). A second important detail is that primitive types cannot be used. Only reference types are compatible with Object"

I typed the body of the main method below, and I put the MemoryCell class in the code section. First of all, what does downcast mean? Second, I understand why primitive types like int and float can't be used, but why does my book say that the toString method is automatically invoked? Thirdly, there are some situations in which primitive types can be passed as arguments into methods of objects?

MemoryCell m = new MemoryCell();

m.write("37");
String val = (String) m.read();
System.out.println("Contents are: " + val);
//
//
//

public class MemoryCell
{
     //Public methods
     public Object read() {return storeValue;}
     public void write(Object x) {storedValue = x;}

     private Object storedValue;
}

Open in new window

0
Comment
Question by:shampouya
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 3
13 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 36513605
0
 

Author Comment

by:shampouya
ID: 36513612
that page doesn't really define it clearly
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36513614



String extends Object so String s = (String) o; - is example of downcasting      

if you want to use methods of String you need to do downcasting, otherwise compiler wuill complain if
you apply those methods to Object instance

Downcasting is allowed when there is a possibility that it suceeds at run time:

Object o = getSomeObject(),
String s = (String) o;
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 47

Expert Comment

by:for_yan
ID: 36513627
Dowbncasting mans casting to a class which inherrits from the current typ
So if o was odeclared of type Object - you cast it tio String which inherist from Ovbject
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36513643
Some methods lilke

write(object) they inside their body do
this

write(Object o){

write(o.toString());


}


so you don't need
to imnvoke them in this way:

write(o.toString())

because this method will take care of getting string fro your object by itself in its body

0
 
LVL 47

Expert Comment

by:for_yan
ID: 36513646
theer fore you can jaust say:

ArrayList ar = ...
System.out.println(ar);

and ptrintln() method will in fact involde toString() method on the argument within its own body - you don't need to worrty  about it
0
 
LVL 3

Expert Comment

by:evedder
ID: 36513651
here is another link with info about downcasting, and example and a brief explanation

http://www.programmerinterview.com/index.php/java-questions/downcasting-in-java/
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36513652
Of course primiteives are being passed as argiuments of the methods very often - why not?

say

Struing s = "1234";

String s2 = s.substring(2);

2 is int and it is passwd as arguiment to String;'s metghod substring() - plenty of times happens
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36513668


Important thing about downcasting is that if you use downcasting in your program
you need to do it explicitly

like

Object o;
String s = (String) o;

If you do upcasting you don't need to mention it expicilty

like

Strung s;

Object o = s;

(no parenthesses with the type is necessary).

Why?

because every instance of String is ALQWAYS
inastance of Object but not vice versa

So compiler needs programmes confirmatuion that he/sshe (programmer)beleives that
this particular object
in fact can be downcast

for upcatsing compiler odes not need it
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36513676
So if you do downcasting without explicit type in parenthese compiler raises an error - in order to
insure you form doing a mistake

Upxcasting is bnever a problem - compiler does not need to worruy that this is a mistake on your part
0
 

Author Comment

by:shampouya
ID: 36513716
So the easy-to-understand definition of downcasting is taking an object of a parent class and then trying to convert into the type of one of the child classes.
0
 
LVL 47

Accepted Solution

by:
for_yan earned 2000 total points
ID: 36513732
yes - you are right
0
 

Author Closing Comment

by:shampouya
ID: 36513744
thanks
0

Featured Post

Build and deliver software with DevOps

A digital transformation requires faster time to market, shorter software development lifecycles, and the ability to adapt rapidly to changing customer demands. DevOps provides the solution.

Question has a verified solution.

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

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
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:
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses

715 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