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?
Well, the reason why you are getting that error is that you are inheriting the "speak" method from the parent class Pet. You have declared speak() method as a public method and then you are inheriting it and making in protected. I suggest you leave it public once you inherit that and override that in the class Dog, Cat, Monkey.
The Speak method will have to be virtual in your base class to override
Pet class
and you must use the same modifier (public)
Dog Class
Pretty sure it is because you are changing a
public
method toprotected
in the subclass.There error is telling you that you cannot change the type of access when overriding the method. So, to fix this just keep the method as public in
Cat
andDog
: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