I have a general OOP question.
If I have the following classes in C#
class Parent
{
public string val = "Parent";
public void getValue()
{
Console.WriteLine(this.val);
}
}
class Child:Parent
{
public string val = "Child";
}
Child child = new Child();
child.getValue();
The code outputs 'Parent'. As I understand it's because this points to Parent object, right?
If I do the same in PHP5:
class ParentClass {
public $val = 'parent';
public function foo()
{
echo $this->val;
}
}
class ChildClass extends ParentClass {
public $val = 'child';
}
$a = new ChildClass();
$a->foo();
The result will be 'child'.
Though if I change
public $val = 'parent';
to
private $val = 'parent';
then PHP will also show 'parent'. C# always return 'parent' with both public and private access modifiers.
Is there any reason for this? And which behavior is correct?
Any useful links to read will be highly appreciated!
Thank you!
There is no correct or incorrect behavior in your stated scenarios. The language designers did what made sense to them.
The reason you don't get the expected behavior in c# is because GetValue is being called in the Parent class, where "this" means the parent val.
To get the correct behavior, you would include the same method in the Child class, with the override keyword:
public class Child
{
public string val = "Child";
public override void GetValue()
{
Console.WriteLine(val);
}
}
...which would print "Child" to the console.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With