AI智能
改变未来

C# 程序设计,设计抽象类Animal,具有类别、速度等属性,具有吃、叫、喜好等抽象方法;设计派生类Dog 、Cat实现抽象方法…比较对象的速度,并给出结果

[code]/// <summary>/// 抽象类:动物/// </summary>public abstract class Animal {protected string type;protected int speed;public string Type => type;public int Speed => speed;public abstract void Talk();public abstract void Eat();public abstract void Love();public override string ToString() {return type;}}
[code]/// <summary>/// 实现类:猫/// </summary>public class Cat:Animal {public Cat(string type,int speed) {this.type = type;this.speed = speed;}public override void Talk() {System.Console.WriteLine(\"喵喵\");}public override void Eat() {System.Console.WriteLine(\"吃鱼\");}public override void Love() {System.Console.WriteLine(\"捉老鼠\");}}
[code]/// <summary>/// 实现类:狗/// </summary>public class Dog:Animal {public Dog(string type, int speed) {this.type = type;this.speed = speed;}public override void Talk() {System.Console.WriteLine(\"汪汪\");}public override void Eat() {System.Console.WriteLine(\"吃肉\");}public override void Love() {System.Console.WriteLine(\"狩猎\");}}
[code]using System;namespace _3_1 {class Program {static void Main(string[] args) {Animal cat = new Cat(\"波斯猫\", 30);Animal dog = new Dog(\"猎犬\", 60);//调用行为cat.Talk();cat.Eat();cat.Love();//调用行为dog.Talk();dog.Eat();//dog.Love();////输出属性,重载ToStringPrintPropertys(cat);PrintPropertys(dog);////比较Console.WriteLine($\"速度更快的是:{(cat.Speed > dog.Speed ? cat.Type : dog.Type)}\");Console.ReadLine();}static void PrintPropertys(Animal animal) {Console.WriteLine($\"类型:{animal.Type}, 速度:{animal.Speed}\");}}}

运行结果:

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » C# 程序设计,设计抽象类Animal,具有类别、速度等属性,具有吃、叫、喜好等抽象方法;设计派生类Dog 、Cat实现抽象方法…比较对象的速度,并给出结果