【c#】类的继承-BookPage79~81

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Animal
    {
        private string type;
        public string Type
        {
            get { return type; }
            set { type = value; }
        }
        public string toString()
        {
            return "这是一个动物类!";
        }
        public void sound()
        {
            Console.WriteLine("动物声音");
        }
        }
    class Cat:Animal
    {
        private string name;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        public string toString()
        {
            return "猫猫的名字是"+name+",属于"+Type+",它会";
        }
        public void sound()
        {
            Console.WriteLine("喵喵叫");
        }
    }
    class Dog : Animal
    {
        private string name;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        public string toString()
        {
            return "狗狗的名字是"+name+",属于"+Type+",它会";
        }
        public void sound()
        {
            Console.WriteLine("汪汪叫");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Dog d = new Dog();
            d.Type = "哺乳类";
            d.Name = "Tom";
            Console.Write(d.toString());
            d.sound();
            Cat c = new Cat();
            c.Type = "哺乳类";
            c.Name = "Ketty";
            Console.Write(c.toString());
            c.sound();
            Animal d1 = new Dog();
            //d1.Name="Jack";  //对象d1不具有Name属性,此句不能通过编译

        }
    }
}
子类(派生类)可调用父类(基类)的非私有方法/数据,父类不可调用子类定义的方法。

自己学的太乱了,先就这么着吧,想学什么学什么。

猜你喜欢

转载自blog.csdn.net/qq_41138935/article/details/80032935