C#抽象类与重载重写实战

一,定义

1,抽象类:用于提供类的部分成员实现 , 包含抽象方法也可以是普通方法,如果抽象方法不用去实现,谁继承这个抽象谁去实现抽象方法 ,抽象类里面也可以定义抽象成员, 如果是抽象成员。 需要在派生类里面去实现成员。

需要重写抽象成员和抽象方法

2,重写: 使用override关键字进行重写

3,重载:函数重载 和 符号重载

【1】,符号重载:把常用算术符号,逻辑运算符号按照自己的定义方式进行运算 能够使对象进行运算

【2】,函数重载:在同一个作用域内定义多个同名函数,但这些函数的参数列表不同(参数类型、数量或顺序不同)。

二,相关习题

1,定义 Student 类,实现Study方法的重载。

相关代码:

namespace yw
{
internal class Program
{
static void Main(string[] args)
{
new Student();

new Student().Study();
new Student().Study("高数");
new Student().Study(150);
new Student().Study("语文", 150);
new Student().Study(120,"英语");

}
}
public class Student
{
public void Study()
{
Console.WriteLine("我在学习");
}
public void Study(string Progect)
{
Console.WriteLine("我在学习"+ Progect);
}
public void Study(int score)
{
Console.WriteLine("我在学习下次考{0}分",score);
}
public void Study(string projict, int score)
{
Console.WriteLine("我在学习{0} 下次考{1}分",projict,score);
}
public void Study(int score ,string project)
{
Console.WriteLine("我在学习{0} 下次考{1}分", project, score);

}
}
}

运行结果:

2,

定义一个抽象类 Animal 包含Name 名称 Color(颜色) Kind(种类) Favorite(喜好)四个属性 ,定义一个 带参数的构造函数,定义一个info的方法 打印以上四个信息,定义抽象的Have方法要求Dog和Cat俩个类继承Animal 实现Have这个抽象方法,狗类打印有骨头吃 猫类打印有鱼吃

相关代码:

namespace Zy
{
internal class Program
{
static void Main(string[] args)
{
Dog a1 = new Dog("小黄", "黄色", "金毛", "骨头");
a1.Info();
a1.Have(1);
Cat a2 = new Cat("小花", "黄色", "布偶", "鱼");
a2.Info();
a2.Have(1);

Console.ReadKey();

}
}
public abstract class Animal
{
public string Name { get; set; }
public string Color { get; set; }

public string Kind { get; set; }
public string Favorite { get; set; }
public Animal(string A, string C ,string K,string F)
{
Name = A;
Color = C;
Kind = K;
Favorite = F;

}

public void Info()
{
Console.WriteLine("姓名 "+Name +" 颜色 "+Color + " 种类 "+Kind +" 喜好 "+Favorite);

}
public abstract void Have(int a);

}
public class Dog : Animal
{
public Dog (string A, string C, string K, string F):base(A, C, K, F)
{

}

public override void Have(int a)
{
Console.WriteLine("有骨头吃");

}

}
public class Cat : Animal
{
public Cat(string A, string C, string K, string F) : base(A, C, K, F)
{

}

public override void Have(int a)
{
Console.WriteLine("有鱼吃");

}

}
}

运行结果:

相关推荐
SmartRadio14 分钟前
ESP32-S3 双模式切换实现:兼顾手机_路由器连接与WiFi长距离通信 (采用Arduino代码框架)
开发语言·智能手机·esp32·长距离wifi
njsgcs24 分钟前
solidworks自动标注折弯4 无向图 c#
开发语言·c#·solidworks
c++之路37 分钟前
C++ 多线程
开发语言·c++
CHANG_THE_WORLD42 分钟前
<Fluent Python > Unicode 文本与字节
开发语言·python
AI人工智能+电脑小能手1 小时前
【大白话说Java面试题】【Java基础篇】第20题:HashMap在计算index的时候,为什么要对数组长度做减1操作
java·开发语言·数据结构·后端·面试·哈希算法·hash-index
凯瑟琳.奥古斯特1 小时前
Bootstrap快速上手指南
开发语言·前端·css·bootstrap·html
我就是妖怪1 小时前
Kimi K2.6 智能效果实测与能力全景展示
开发语言
中二痞1 小时前
下载Python 版本,环境变量变更以及PyCharm更换python版本
开发语言·python·pycharm
故事和你911 小时前
洛谷-算法2-3-分治与倍增5
开发语言·数据结构·c++·算法·动态规划·图论