Regarding simple inheritance in C#
I have a question regarding simple inheritance in C#.
Here is the code:
class Mammal
{
int age { get; set; }
public Mammal(int age)
{
this.age = age;
}
}
class Dog : Mammal
{
string breed { get; set; }
public Dog(int age, string breed)
: base(age)
{
this.breed = breed;
}
}
class Program
{
static void Main(string[] args)
{
Dog joe = new Dog(8, "Labrador");
Console.WriteLine("Joe is {0} years old dog of breed {1}", joe.age,
joe.breed); // gives error
}
}
This gives error since it cannot access the age and breed parameters. So I
make age and breed public in Mammal and Dog class respectively. This makes
the program to run fine.
But my question is shouldn't ideally the parameters be made private or
non-public and only accessed through public methods? If that's the case,
then how can I access the non-public parameters in Program class?
Thanks
No comments:
Post a Comment