今天我们来看到~物件导向的三大特性~
什麽是物件呢~ 物件是指类别的实例。
例如,有一个类别是Car,我们可以将它实例化。
Car car=new Car(); //(小写的)car就是物件
物件是物件导向程序的基本单位,它将程序和资料装进去,提高软件的重用性、灵活性和扩充性。
因此,我们可以用物件来存取及修改物件中的相关资料。
知道物件导向的基本概念後,我们去探究它的三大特性吧,封装、继承、多型~
学习目标: C#三大特性的概念
学习难度: ☆☆☆
封装顾名思义就像是将一堆汽车零件(栏位、属性、方法)封装到汽车中(类别)。
例如,有一个类别是Car,我们可以将Car的相关资料存放在类别中。
public class Car
{
public int weight=10;
private string brand=toyota; //brand用在Car类别的运算
public string Brand //Name用在外部类别的读取
{
get{return brand;} //外部读取时会return toyota (brand)
set{brand=value;}
}
}
因此,我们要使用时,就能用Car去使用里面的资料拉(weight, brand)~
例如,有一个业务员的类别,他想知道汽车的品牌是什麽。
我们就可以透过Car去读取品牌的名字~
public class Bussiness
{
Car car=new Car();
Console.WriteLine("汽车的品牌是"+car.Brand);
}
继承是指一个类别(子类别)去继承另一个类别(父类别)的概念。
有点像小孩会继承父亲的特性~
所以子类别就能使用父类别的资料拉~
我们来看到继承是如何被实现的。
public class Father
{
public string name="William";
}
public class Child : Father
{
}
public calss Introduction
{
Father father=new Father();
Child child=new Child();
child.name="Wilson";
Console.WriteLine(father.name); //印出William
Console.WriteLine(child.name); //印出Wilson
}
重点来拉~ Child中的name就不用在重新宣告了~
这样程序码是不是就简洁多了呢~
接着~我们来看看其他继承相关的规则~
C#只有单一继承没有多重继承~
意思就是Child只能继承Father~ 不能在继承其他类别~
另外~在设计的时候~ 继承的子类别要尽量与父类别有依存关系~
例如~ 面包是食物~ 汽车是交通工具~ 小孩是父亲的
多型是指父类别为子类别提供统一的虚拟(virtual)方法,子类别可以覆盖(override)父类别的方法。
换句话说,子类能使用父类别的虚拟方法,但他们能输出不一样的结果。
那我们来看一个例子吧~
public class Father //父类别
{
public string words;
public virtual string Talk() //父类别宣告虚拟方法
{
words = "I can talk, and I am a father";
return words;
}
}
public class Child1:Father //子类别,Child1
{
public override string Talk() //子类别复写虚拟方法
{
words = "I can talk too, and I am a child 1";
Console.WriteLine(words + "\n");
return words;
}
}
public class Child2 : Father //子类别,Child2
{
public override string Talk() //子类别复写虚拟方法
{
words = "I can talk too, and I am a child 2";
Console.WriteLine(words + "\n");
return words;
}
}
class MainProgram
{
static void Main()
{
Child1 child1 = new Child1();
Child2 child2 = new Child2();
Father[] fathers = { child1, child2 }; //宣告父类别的阵列,装子类别
foreach (Father father in fathers)
{
father.Talk(); //让父类别阵列的子类都讲话
}
}
}
参考资料:
https://www.youtube.com/watch?v=nYCMW3kfTvs&feature=youtu.be&ab_channel=BroCode
前几天画完流程图 今天来介绍 从资料库的设计 (我们其实是很後期要整理专案时才回来画 不是照着步骤设...
今天的目标 要怎麽简单快速地做出客制化地文件?今天,我们会教用 GAS 搭配 Goolge Doc。...
经过这两篇CreateML建立机器学习模型与如何提升判断准确度的教学相信大家都学会了该如何制作Cr...
数组 array(): 生成一个数组 range(): 创建并返回一个包含指定范围的元素的数组 co...
「强硬的将变数改变型态会发生什麽问题?」诗忆好奇地发问。 「什麽都可能发生。」 唯心从包里掏出一张纸...