多态是其面向对象中其非常重要的一个组成部分,其主要作用在于:程序的多次利用,重用
重载相信大家非常熟悉就在这不予说明了
接口
目的是方便统一管理.另一个是方便调用.
这个就叫统一访问,因为你实现这个接口的类的方法名相同,但是实现内容不同
我用接口来定义对象不就可以做到统一访问了吗?接口主要针对多个类实现它来说的,要是只有一个类当然可以不用接口了.你这样想,我做一个USB接口,有个read()抽象方法,然后mp3类实现,U盘类实现,移动硬盘类实现,这样我用的时候用USB a=new 【类名】;这样a.read();要是我类名里写U盘,就读U盘,写mp3就读mp3,而这个名字可以从属性文件里读,你写哪个就用哪个了
为什么要用接口 :用于处理多变的情况。
接口在实际开发过程中最大好处是,你可以按照设计,先把接口写好,然后分配大伙干活的时候,告诉a们去用写好的接口去实现他们的具体功能,而告诉b们,去写那些已经写好但是没有具体的代码的接口,这样可以提高工作效率。并且底层和应用也通过接口做了一个很明显的分层。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 接口
{
public class Program
{
static void Main(string[] args)
{
USB a = new U盘();
a.Read();
USB b = new 移动硬盘();
b.Read();
USB c = new 手机();
c.Read();
USB2 d = new 手机();
d.Read();
d.Run();
Console.ReadKey();
}
}
public interface USB
{
string Name
{
get;
set;
}
void Read();
}
public interface USB2 : USB
{
void Run();
}
class U盘 : USB
{
public string Name
{
get;
set;
}
public void Read()
{
Console.WriteLine("读出U盘数据");
}
}
class 移动硬盘 : USB
{
public string Name
{
get;
set;
}
public void Read()
{
Console.WriteLine("读出移动硬盘数据");
}
}
class 手机 : USB2
{
public string Name
{
get;
set;
}
public void Read()
{
Console.WriteLine("读出手机数据");
}
public void Run()
{
Console.WriteLine("跑手机");
}
}
}
虚函数
多态中的虚函数 虚函数必须与原函数同名
派生类可以用基类的东西 而基类指向派生类后 基类不能使用 派生类的东西
在基类指向派生类时 虚函数就会被覆盖
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 多态
{
class Program
{
static void Main(string[] args)
{
B b = new B();
A a = new A();
a.F();
a.G();
b.S();
b.G();
a = b;
a.F();
a.G();
Console.ReadKey();
}
}
class A
{
public void F()
{
Console.WriteLine("AdeM");
}
public virtual void G()
// public void G()
{
Console.WriteLine("AdeN");
}
}
class B:A
{
public void S()
{
Console.WriteLine("BdeM");
}
public override void G()
// public void C()
{
Console.WriteLine("BdeN");
}
}
}
抽象类 抽象方法
传参时可以在参数中写基类 就可以在函数中调用所有派生类
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml;
using System.Net;
using System.Net.Sockets;
namespace 泛型
{
class Program
{
static void Main(string[] args)
{
// s<int> ss = new s<int>(5);
// int[] a;
Person peree = new Person()
{
Age = 18
};
p(peree);
Console.ReadKey();
}
public static void p(per p)
{
p.say();
}
}
class per
{
virtual public void say()
{
Console.WriteLine("per");
}
}
class Person:per
{
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
override public void say()
{
Console.WriteLine(age);
}
}
class Student:d
{
private int age;
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
public int Age
{
get { return age; }
set { age = value; }
}
public void say()
{
Console.WriteLine(age+name);
}
}
interface d
{
void say();
}
}