• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Determining the type of an object?

 
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello

I was wondering, if I have an interface that is implemented by several classes, (lets say Shape)
and I've created an object of this type like this

Shape s;
s = new Rectangle();
// after few method calls I change the type of s to be triangle
s = new Triangle();

then how can I determine what type of shape s in this case? in other words, how can I know if s is now a triangle or rectangle?

is there a method in Java that checks the actual type of the object?

Thanks
HannaH
 
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think declaring a method in another class, which will accept the argument of superclass and it's subclass at runtime is the fine solution of it. This is also called polymorphism.
[ October 24, 2008: Message edited by: Pawan Arora ]
 
Ranch Hand
Posts: 82
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can use:

 
Ranch Hand
Posts: 457
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
and then you can call isAssignableFrom
 
H Melua
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks guys very much
That works
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can also use the instanceof operator.

But in general, using these techniques is a sign for a design that doesn't make full use of the advantages of OOP, especially polymorphism.

Why do you feel the need to do it?
reply
    Bookmark Topic Watch Topic
  • New Topic