You extend a class by adding a colon to the end of class declaration, followed by the base class to inherit from.
class Bird {
public void Fly() {
// here’s the code to make the bird fly
}
public void LayEggs() { ... };
public void PreenFeathers() { ... };
}
class Pigeon : Bird {
public void Coo() { ... }
}
A subclass can override methods to change or replace methods it inherited
Sometimes you’ve got a subclass that you’d like to inherit most of the behaviors from the base class, but not all of them. When you want to change the behaviors that a class has inherited, you can override the methods.
A subclass can only override a method if it’s marked with the virtual keyword, which
tells C# to allow the subclass to override methods.
class Bird {
public virtual void Fly() {
// code to make the bird fly
}
}
Add a method with the same name to the derived class
You’ll need to have exactly the same signature—meaning the same return value and
parameters—and you’ll need to use the override keyword in the declaration
class Penguin : Bird {
public override void Fly() {
MessageBox.Show(“Penguins can’t fly!”)
}
}
class Bird {
public void Fly() {
// here’s the code to make the bird fly
}
public void LayEggs() { ... };
public void PreenFeathers() { ... };
}
class Pigeon : Bird {
public void Coo() { ... }
}
A subclass can override methods to change or replace methods it inherited
Sometimes you’ve got a subclass that you’d like to inherit most of the behaviors from the base class, but not all of them. When you want to change the behaviors that a class has inherited, you can override the methods.
A subclass can only override a method if it’s marked with the virtual keyword, which
tells C# to allow the subclass to override methods.
class Bird {
public virtual void Fly() {
// code to make the bird fly
}
}
Add a method with the same name to the derived class
You’ll need to have exactly the same signature—meaning the same return value and
parameters—and you’ll need to use the override keyword in the declaration
class Penguin : Bird {
public override void Fly() {
MessageBox.Show(“Penguins can’t fly!”)
}
}
Comments
Post a Comment