当前位置:网站首页>C# 一周入门高级编程之《C#-继承》Day One
C# 一周入门高级编程之《C#-继承》Day One
2022-08-03 07:59:00 【太阳风暴】
一、继承是什么
继承是面向对象程序设计中最重要的概念之一。所谓继承,很明显,其实就是存在着两代或多代类,通过一种方式来将这继承关系的两代或者多代的功能给合成下来。这样就可以把功能组件化,同时也有利于重用代码和节省开发时间。
当创建一个类时,我们其实并不完全需要重新编写新的数据成员和成员函数,只需要设计一个新的类,继承了已有的类的成员即可。同时可以在该成员基础上进一步修改
二、基类和派生类
- 基类:就是初代的那个类
- 派生类:就是继承基类的类
就像动物 是 猫科动物、犬科动物的基类,而猫科动物又是老师的基类,存在着这样的衣襟带水的关系。
class Animal
{
public void setSpeed(int v)
{
speed = w;
}
public void setTime(int h)
{
time= h;
}
protected int speed;
protected int time;
}
// 派生类
class Cat: Animal
{
public int getLength()
{
return (speed * time);
}
}
三、基类初始化
基类的初始化有很多种方法,基类总是先被初始化然后派生类再初始化的。
派生类继承了基类的成员变量和成员方法。因此父类对象应在子类对象创建之前被创建。那我们可以在成员初始化列表中对父类的初始化。使用的关键字就是 base
class Animal
{
// 成员变量
protected double speed;
protected double time;
public Animal(double v, double t)
{
speed = v;
time = t;
}
public double GetLength()
{
return speed * time;
}
public void Display()
{
Console.WriteLine("速度: {0}", speed);
Console.WriteLine("时间: {0}", time);
Console.WriteLine("路程: {0}", GetLength());
}
}
class Cat: Animal
{
private double cost;
public Cat(double v, double t) : base(v, t)
{
}
public double GetCost()
{
double cost;
cost = GetArea() * 70;
return cost;
}
public void Display()
{
base.Display();
Console.WriteLine("价格: {0}", GetCost());
}
}
四、使用接口的多继承
C#是不支持C++的那种多继承的方式的,但是还是给我们提供了一个 通过接口的方式继承,当然既然是接口继承得话,那继承接口的方法肯定是必须自己手写的。这其实也不算是多继承,我个人觉得。
代码如下:
class Shape
{
public void setWidth(int w)
{
width = w;
}
public void setHeight(int h)
{
height = h;
}
protected int width;
protected int height;
}
// 基类 PaintCost
public interface PaintCost
{
int getCost(int area);
}
// 派生类
class Rectangle : Shape, PaintCost
{
public int getArea()
{
return (width * height);
}
//重写的接口函数,并没有真正继承到功能
public int getCost(int area)
{
return area * 70;
}
}
边栏推荐
- mysql5.7服务器The innodb_system data file 'ibdata1' must be writable导致无法启动服务器
- ceph简介
- 面渣逆袭:MySQL六十六问,两万字+五十图详解
- Daily practice of PMP | Do not get lost in the exam-8.2 (including agility + multiple choice)
- Windows安装MySQL(MIS)
- 并发之多把锁和活跃性
- pyspark---low frequency feature processing
- Redis分布式锁
- 《21天精通TypeScript-5》类型注解与原始类型
- 加载properties文件,容器总结
猜你喜欢
随机推荐
ArcEngine (3) zoom in and zoom out through the MapControl control to achieve full-image roaming
积分商城系统设计
AI mid-stage sequence labeling task: three data set construction process records
ArcEngine(一)加载矢量数据
Mysql的in和exists用法区别
Redis分布式锁
Charles抓包工具学习记录
IDEA2021.2安装与配置(持续更新)
图解Kernel Device Tree(设备树)的使用
最佳高质量字体
JS函数获取本月的第一天和最后一天
依赖注入(DI),自动配置,集合注入
ArcEngine(二)加载地图文档
品牌方发行NFT时,应如何考量实用性?
[Kaggle combat] Prediction of the number of survivors of the Titanic (from zero to submission to Kaggle to model saving and restoration)
ArcEngine(四)MapControl_OnMouseDown的使用
并发之ReentrantLock
DeFi明斯基时刻:压力测试与启示
requests库
mysql服务器上的mysql这个实例中表的介绍









