This is my first time working with classes, so excuse my ignorance.
I have a Pet class that is my base class. I have two children classes, Dog and Cat. What I’m trying to do is have the Cat and Dog methods override the Pet method by saying “Woof!” and “Meow!” instead of speak. Then in another form I have to print the information (name, color, and them speaking) on a button press.
class Pet
{
protected string name, color, food;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string Color
{
get
{
return color;
}
set
{
color = value;
}
}
public string Food
{
get
{
return food;
}
set
{
food = value;
}
}
public void speak(string s)
{
s = "Speak";
MessageBox.Show(s);
}
public Pet(string name, string food, string color)
{
//Constructor
this.Food = food;
this.Name = name;
this.Color = color;
}
class Dog : Pet
{
public Dog(string name, string food, string color)
: base(name, food, color)
{
}
protected override void speak()
{
}
}
}
(left out the cat because it’s the same as dog pretty much)
I keep getting the error “Error 1 ‘Lab12.Cat.speak()’: cannot change access modifiers when overriding ‘public’ inherited member ‘Lab12.Pet.speak()’ ”
What am I doing wrong? I know it has to do with protection levels somewhere, and I keep switching things from public to protected or private, but it isn’t fixing anything. Help, anybody?
Since Speak() was originally public, you need to keep it public. You “cannot change access modifier” (public vs private).
Also, you cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.
Take a read: http://msdn.microsoft.com/en-us/library/ebca9ah3(v=vs.100).aspx