C#中的继承举例

源码:

using System;

namespace Inherit
{
    public class Person
    {
        public string name; //定义域
        public int age;
        virtual public void SayHello()
        { //定义方法 //virtual表示可以被子类override
            Console.WriteLine("Hello!  My name is " + name);
        }
        public void SayHello(Person another)
        {  //构造方法重载同名的sayHello方法
            Console.WriteLine("Hello," + another.name +
                "! My name is " + name);
        }
        public bool IsOlderThan(int anAge)
        { //定义方法
            bool flg;
            if (age > anAge) flg = true; else flg = false;
            return flg;
        }
        public Person(string n, int a)
        { //构造方法
            name = n;
            age = a;
        }
        public Person(string n)
        { //构造方法重载
            name = n;
            age = -1;
        }
        public Person() : this("", 0)//调用其他构造方法
        {
        }
    }


    public class Student : Person  //定义子类
    {
        public string school; //增加的字段
        public int score = 0;
        public bool isGoodStudent()
        { //增加的方法
            return score >= 90;
        }
        override public void SayHello()
        { //override覆盖父类的方法
            base.SayHello();
            Console.WriteLine("My school is " + school);
        }
        public void SayHello(Student another)
        { //增加的方法
            Console.WriteLine("Hi!");
            if (school == another.school)
                Console.WriteLine(" Shoolmates ");
        }

        public Student()
        {  //构造方法
        }
        public Student(string name, int age, string school)
            : base(name, age) //调用父类的构造方法
        {
            this.school = school;
        }

        public void TestThisSuper()
        {
            int a;
            a = age;      //本句与以下两句效果相同
            a = this.age; //使用this
            a = base.age; //使用base
        }
    }
        class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person("Liming", 50);
            Student s = new Student("Wangqiang", 20, "PKU");
            Person p2 = new Student("Zhangyi", 18, "THU");
            Student s2 = (Student)p2; //类型转换
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值