Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Object-oriented language basics, Part 4

Inheritance: Build objects in layers

  • Print
  • Feedback

Page 8 of 10

Point p = new Circle (10.0, 20.0, 30.0);


This code creates a Circle object and assigns its reference to p -- an object reference variable of the Point reference type. Using p, you can call getX() and getY() to access the x and y field values. But can you call getRadius()?

You can't: The Circle layer, rather than the Point layer, declares getRadius(). In essence, getRadius() belongs to Circle and not to Point. The only way to use p to access getRadius() is with a cast, like this:

double radius = ((Circle) p).getRadius ();


Once variable p's type casts to Circle (by way of the (Circle) cast), you can call getRadius().

Although it is legal to cast a subclass reference to a superclass reference, the reverse is illegal. Consider the following code fragment:

  • Print
  • Feedback

Resources