您的位置:首页 > 编程语言 > C#

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!");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: