General question about inheritance

G

Guest

Hi!

I'm just starting out in C# and I am wondering why the Cow objects gets a
"inaccessible due to protection level" in the following code:

namespace ClassesAndInheritance
{
class Program
{
static void Main(string[] args)
{
Cow myCow = new Cow();
myCow.EatFood();
Console.ReadKey();
}

}

class Animal
{
protected void EatFood()
{
Console.WriteLine("Mmmm... Yummy! I am an animal...");
}
protected void Breed()
{
Console.WriteLine("Hey! Here comes another!");
}

}
class Cow : Animal
{
protected void Moo()
{
Console.WriteLine("Moooo!");
}
protected void SupplyMilk()
{
Console.WriteLine("I am a cow... I give you milk...");
}

}
}
 
M

Michael Groeger

Because you declared EatFood() as protected. Protected members are only
accessible from inherited classes, but not from outside. You have to declare
EatFood() as either public (make it accessible for everyone) or as internal
(public for everyone within the same assembly).

Michael
 
T

Truong Hong Thi

Method EatFood is declared as protected. You cannot access it from
Program which is not a subclass of Animal.

I think that Console class does not have ReadKey method.
 
J

JDC

Hi,

You get that error because EatFood() is only visible to the Animal
class, and classes derived from it (i.e. Cow).

Perhaps if you never intend to create an Animal directly, you could
think about making it abstract, and using virtual methods:

abstract public class Animal
{
public virtual void EatFood()
{
Console.WriteLine("Mmmm... Yummy! I am an animal...");
}
}

public class Cow : Animal
{
public override void EatFood()
{
base.EatFood();
Console.WriteLine("...and I'm eating cow feed!");
}

}

Notice how EatFood() is now publicly accessible to your Main() method.

Cheers, J
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top