Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

upcasting ^^^

 
Alex Black
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
During an upcast like
A a = new A();
A b = new B();
B extends A{}
Does this mean that b can no longer access
the methods in B() and only the methods of A?
thanks
 
Sean Casey
Ranch Hand
Posts: 625
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, b still accesses all of the methods of B. Keep in mind, that the object is a new B() while the reference is of the supertype A.
 
Ravindra Mohan
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Alaxander and Sean,
Well let me clarify at the outset what is been done by the
code . I have given the explaination in my code below:


Hope the issue is clear now.
Cheers,
Ravindra Mohan.
[This message has been edited by Ravindra Mohan (edited May 05, 2001).]
 
Stevie Kaligis
Ranch Hand
Posts: 400
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Ravindra...,
a litle correction, on your code, if 'b' want's to access method on class B, it can not dirrectly acces the method, you must downcast it first, because object only knows their type.
here is the code :
class A {
void f() {}
}
public class B extends A{
void g() {}
public static void main(String[] args) {
A a = new A();
A b = new B();
// b.g(); //compile error !! can not dirrectly
b.f(); //OK !
((B)b).g(); //downcast = OK!
}
}

regards,
stevie
 
Alex Black
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Stevie
That's a really cool answer you gave, thanks.
Regards
Alex
 
Ravindra Mohan
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Calligis,
Well, let me clarify here. I did not say how the reference of
object of superclass would refer to the methods of subclass methods.
I simply stated a point that an object of subclass inherits the public/protected methods/members of superclass.
Where is the confusion?? Ofcource, a reference variable of superclass only knows about the methods that are defined in the superclass and cannot know the methods that are declared and defined in the subclass, precisely that is what is implemented when we use abstraction.
Cheers,
Ravindra Mohan.

[This message has been edited by Ravindra Mohan (edited May 06, 2001).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic