Please consider the following code:
class baseclass {
public $hideme;
public function getit() { return $this->hideme; }
public function setit($value) { $this->hideme = $value; }
}
class derived extends baseclass {
private $hideme; //can't do this
private function getit() { //can't do this
return 0;
}
}
function doobee(baseclass $obj) {
echo $obj->getit() . "\n";
}
On the other hand in java language you can do that with properties. Also, even in php you can do the other way around, that is, a private
property in the base class can be redefined as public in the child class, because it creates a new property in child class, instead of overriding. Why can't it do same when redeclaring public property as private in the child class?
This answer on SO says, The rationale being you shouldn't be able to hide members from the base class.... but, we are not hiding anything from base class!, base class's objects will still have access to those public properties and function. Its just the child classes' objects have either two versions(private and public) of same property or just the visibility be overridden?.
What if I want just any grandchild classes inheriting from child(
derived
in code) class not have public properties of grandfather class($hideme
inbaseclass
)?If it is a general rule of inheritance in oop as the SO answer suggest, why is not valid in java?
What's up with the methods? #1 also applies to methods as well.
P.S: Please note that #1,#2 and #3 are not three different questions. Asking them as three different questions wouldn't make sense as they all circle around the same problem.