c#面向对象特征(1)之继承
2016-06-02 10:51
330 查看
c#中类不能多重继承
基类中的virtual函数可以在子类中重写,也可以不重写。子类的实例化对象都会继承基类中的函数。
sealed用在类前表示关闭类即该类无法被继承
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication1Another;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Dog dog = new Dog();
dog.age = 10;
dog.Byte();
//抽象函数没有被重写也可以被子类继承
dog.GetAge();
dog.BitMan();
Console.ReadLine();
}
}
class Animal {
public int age
{
get;
set;
}
//抽象函数--需要在继承的子类中实现
public virtual void Byte() {
Console.WriteLine("Animal byte!");
}
//不重写也可以被子类继承
public virtual void GetAge() {
Console.WriteLine(age);
}
//不用重写,如果重写的话则在子类中对应的函数需要添加new关键字,否则编译不通过
public void BitMan() {
Console.WriteLine("Animal bite man!");
}
}
//overrade重写Byte()
sealed class Dog : Animal//sealed表示该类无法被继承
{
public override void Byte()
{
Console.WriteLine("Dog byte!");
}
public new void BitMan() {//new 关键字使得基类中的方法被隐藏。
Console.WriteLine("Dog bit man!");
}
}
}
基类中的virtual函数可以在子类中重写,也可以不重写。子类的实例化对象都会继承基类中的函数。
sealed用在类前表示关闭类即该类无法被继承
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication1Another;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Dog dog = new Dog();
dog.age = 10;
dog.Byte();
//抽象函数没有被重写也可以被子类继承
dog.GetAge();
dog.BitMan();
Console.ReadLine();
}
}
class Animal {
public int age
{
get;
set;
}
//抽象函数--需要在继承的子类中实现
public virtual void Byte() {
Console.WriteLine("Animal byte!");
}
//不重写也可以被子类继承
public virtual void GetAge() {
Console.WriteLine(age);
}
//不用重写,如果重写的话则在子类中对应的函数需要添加new关键字,否则编译不通过
public void BitMan() {
Console.WriteLine("Animal bite man!");
}
}
//overrade重写Byte()
sealed class Dog : Animal//sealed表示该类无法被继承
{
public override void Byte()
{
Console.WriteLine("Dog byte!");
}
public new void BitMan() {//new 关键字使得基类中的方法被隐藏。
Console.WriteLine("Dog bit man!");
}
}
}
相关文章推荐
- C# 设计模式系列教程-抽象工厂模式
- C#命名规则和风格
- C# 设计模式系列教程-建造者模式
- C# 设计模式系列教程-原型模式
- 【代码】C#生成指定长度的随机数方法
- C# 设计模式系列教程-单例模式
- C# 设计模式系列教程-工厂方法模式
- C#代码示例_集合
- C#创建Windows Service(Windows 服务)基础教程
- C# 加密
- WPF C# 字符串读写文件
- C# 格式化字符串
- C#将dll打包到程序中
- C# wpf 列出文件夹所有文件
- C# 获得系统环境
- C# 6.0 $"Hello {csdn}"
- C# wpf 使用资源文件 resx
- C# wpf image绑定viewModel没有显示图片
- Wpf基础之数据绑定
- 反射技术实现DataTable到实体类的赋值操作