Author Topic: Accessing superclass variables  (Read 1845 times)

ober

  • Ashton Shagger
  • Ass Wipe
  • Posts: 14305
  • Karma: +73/-790
  • mini-ober is taking over
    • Windy Hill Web Solutions
Accessing superclass variables
« 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?

webwhy

  • Jackass IV
  • Posts: 608
  • Karma: +15/-10
Re: Accessing superclass variables
« Reply #1 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(102040);
echo 
$c->getExtra() . "\n";


« Last Edit: March 07, 2011, 03:19:34 PM by webwhy »

ober

  • Ashton Shagger
  • Ass Wipe
  • Posts: 14305
  • Karma: +73/-790
  • mini-ober is taking over
    • Windy Hill Web Solutions
Re: Accessing superclass variables
« Reply #2 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.

Perspective

  • badfish
  • Jackass In Charge
  • Posts: 4635
  • Karma: +64/-22
    • http://jeff.bagu.org
Re: Accessing superclass variables
« Reply #3 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".

webwhy

  • Jackass IV
  • Posts: 608
  • Karma: +15/-10
Re: Accessing superclass variables
« Reply #4 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.

ober

  • Ashton Shagger
  • Ass Wipe
  • Posts: 14305
  • Karma: +73/-790
  • mini-ober is taking over
    • Windy Hill Web Solutions
Re: Accessing superclass variables
« Reply #5 on: March 07, 2011, 04:47:55 PM »
Thanks.  I should have thought of that.