Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Does casting apply to references or to objects? (was Doubt???)

 
Shiaber Shaam
Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When we type cast object references..... we are casting the references or objects.... Plz clarify......
[ July 27, 2006: Message edited by: Barry Gaunt ]
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Plz? Postleitzahl? What place do you need the Postleitzahl of? Z�rich is 8001.

Please use real words - or are you using a mobile phone to access the internet?

Perhaps this will help you understand casting
[ July 27, 2006: Message edited by: Barry Gaunt ]
 
Shiaber Shaam
Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Plz apologize me if it is not meaningful or it violated the policies of the forum... But i am not clear with the doubt.... So plz clarify........
 
Ramamoorthy Periasamy
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
we are actually casting a reference variables to objects.

class Animal {
}
class Dog extends Animal {
}
public class DogTest {
void go() {
Dog d = new Dog();
Animal a = new Dog();
Animal a1 = d; // doesn't require a cast for downcasting
Dog d1 = (Dog)a; // requires explicit cast for upcasting
}
}
 
Ramamoorthy Periasamy
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the earlier given example, make sure the reference variable passes the is-a condition (instanceof) with the object to be typecasted, otherwise we will get runtime exception

Animal a = new Animal();
Dog d = (Dog)a; // throws runtime exception
 
Shiaber Shaam
Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can u make it more clear... I cant get ur point.......
 
Shiaber Shaam
Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class A{}
class B extends A{}
class Test
{
public static void main(String args[])
{
A a1 = new A();
B b1 = new B();
A a1 = (A)b1; //after executing this the right hand side will
//have object of type A or B
//i.e the ref gets casted or the object itself
//gets casted
}
}
 
fred rosenberger
lowercase baba
Bartender
Posts: 12196
35
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Shiaber,

please read this. We really prefer people to spell out words, rather than using the shorthand style common to text messages.

thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic