The forums have permanently moved to forum.kirupa.com. This forum will be kept around in read-only mode for archival purposes. To learn how to continue using your existing account on the new forums, check out this thread.


Results 1 to 4 of 4

Thread: [Java] Using a subclass' function

  1. #1

    [Java] Using a subclass' function

    I have a superclass Shape and many subclasses: Sphere, Cube, Cylinder, etc... Each of these subclasses extends Shape with a function called printData().

    PHP Code:
    Shape[] shapes = new Shape[3];
    shapes[0] = new Sphere();
    shapes[1] = new Cube();
    shapes[2] = new Cylinder();

    shapes[0].printData(); 
    I cannot figure out how to call printData(). The compiler seems to be looking into Shape.java for the printData() method, whearas it should have been looking in the subclass for it.

    Code:
    main.java:89: cannot find symbol
    symbol  : method printData()
    location: class Shape

  2. #2
    You need to cast the reference first:
    Code:
    ((Sphere) shapes[0]).printData();
    However, you're going to run into problems if you defined that method separately on each class without defining it on the parent class (because it would be difficult to cast to an unknown type in a loop). There are a bunch of ways to solve that problem, though. You could make an interface named something like IPrintable and add printData to that, you could make Shape an abstract class if you don't need to instantiate it ever, or you could make a less useful printData method on the Shape class (that approach is similar to the abstract class approach).

  3. #3
    PHP Code:
    Shape[] shapes = new Shape[3];
    shapes[0] = new Sphere();
    shapes[1] = new Cube();
    shapes[2] = new Cylinder();

    if(
    shapes[0] instanceof Sphere
        
    shapes[0] = (Sphere)shapes[0];

    shapes[0].printData(); 
    I added that before calling the subclass method, but I still get the same error.

    Edit: And then I tried your method, and it worked...... hmmmmmm???
    Last edited by NeoDreamer; September 7th, 2008 at 12:10 AM.

  4. #4
    When you cast using non-primitive datatypes, you are basically just shutting the compiler up while it validates the expression in which you used the cast. The shapes array elements are still known to the compiler to be regular Shapes, and you can't change that permanently unless you choose a different type when declaring your array.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  

Home About kirupa.com Meet the Moderators Advertise

 Link to Us

 Credits

Copyright 1999 - 2012