抽象类和接口

来源:互联网 发布:怎样输入单变量数据 编辑:程序博客网 时间:2024/05/18 01:25
相同点
必须实现父类的抽象方法
都不能直接实例化
不同点
多继承接口  
接口里只能有声明
抽象类里的可以有非抽象方法体
接口里的方法 默认是public

接口和抽象类可以间接实例(里氏转换)
接口    名字=new  子类;

接口是有一个共同的功能 (接口抽象类他能包容 所有继承他的子类)
抽象类 是指子类里面有共同点
//变颜色
usingUnityEngine;
usingSystem.Collections;

publicinterfaceISetColor
{
   voidSetColor(Colorcolor);
}
publicclassJieKou:MonoBehaviour{
   voidOnTriggerEnter(Colliderother) {
       //定义一个接口类型去接收 other上的接口
       ISetColori = other.GetComponent<Sphere>();
       //或者单独获得里面的接口
       //ISetColor s = other.GetComponent<ISetColor>();
       //  MonoBehaviour m = other.GetComponent<MonoBehaviour>();
       if(i!=null)
        {
            i.SetColor(Color.red);
        }
    }
}
-----------------------------------------------------
usingUnityEngine;
usingSystem.Collections;
usingSystem;


publicclassSphere:MonoBehaviour,ISetColor
{
   publicvoidSetColor(Colorcolor)
    {
        GetComponent<MeshRenderer>().material.color = color;
    }
}