EntropySink

Technical & Scientific => Programming => Topic started by: ober on March 07, 2011, 02:45:41 PM

Title: Accessing superclass variables
Post by: ober on March 07, 2011, 02:45:41 PM
I've been out of the OO game for way too long.  Help me!

Class structure:

Writer
   GenericChartWriter
        SpecificChartWriter

I have variables defined in GenericChartWriter like height, width, etc. that I want to reference in the init for SpecificChartWriter. 

I want to call the GenericChartWriter's 'getHeight' method but Eclipse isn't even giving me that as an option.  How do I reference that superclass method from the subclass?
Title: Re: Accessing superclass variables
Post by: webwhy on March 07, 2011, 03:09:25 PM
assuming they are instance variables it's perfectly fine, as long as base class constructor is used to ensure class is properly initialized.



class Base {
  function __construct($height, $width) {
    $this->height = $height;
    $this->width = $width;
  }

  function getHeight() {
    return $this->height;
  }

  function getWidth() {
    return $this->width();
  }
}

class Child extends Base {
  function __construct($height, $width, $extra) {
    parent::__construct($height, $width);
    $this->extra = $extra * $this->getHeight();
  }

  function getExtra() {
    return $this->extra;
  }
}

$c = new Child(10, 20, 40);
echo $c->getExtra() . "\n";


Title: Re: Accessing superclass variables
Post by: ober on March 07, 2011, 03:21:47 PM
FUCK YOU JAVA!

OK, so to access a superclass method, apparently I have to say "super.getHeight()". 

FUCKIN A.
Title: Re: Accessing superclass variables
Post by: Perspective on March 07, 2011, 03:36:06 PM
You can just use "getHeight()" and it will default to the parent function. If you say "super.getHeight()" it will go to the parent even if the child overrides "getHeight".
Title: Re: Accessing superclass variables
Post by: webwhy on March 07, 2011, 03:39:43 PM
sorry i just assumed PHP...

Quote
You can just use "getHeight()" and it will default to the parent function. If you say "super.getHeight()" it will go to the parent even if the child overrides "getHeight".

this is an important distinction and it's import to understand it.
Title: Re: Accessing superclass variables
Post by: ober on March 07, 2011, 04:47:55 PM
Thanks.  I should have thought of that.