志在指尖
用双手敲打未来

C#Protected和多态

Protected在基类中界说后,能被派生类调用,但是不能被其他类调用。
virtual在基类中界说后,在派生类中能被重写。
usingSystem;usingSystem.Collections.Generic;usingSystem.Text;namespace承继
{classVertebrate
{protectedstringspine;//受维护的字段privatedoubleweigth;privatedoubletemperature;publicdoubleWeigthC#
{set{if(value<0)
{
weigth=0;
}else{
weigth=value;
}
}get{returnweigth;}
}publicdoubleTemperature
{set{if(value<0)
{
temperature=0;
}else{
temperature=value;
}
}get{returntemperature;}
}publicVertebrate()
{
spine=”脊柱”;
weigth=0;
temperature=0;
}publicvirtualvoidBreate()//虚办法{
Console.WriteLine(“呼吸”);
}publicvoidSleep()
{
Console.WriteLine(“睡觉”);
}
}
}
usingSystem;usingSystem.Collections.Generic;usingSystem.Text;namespace承继
{classProgram
{staticvoidMain(string[]args)
{
Vertebratevertebrate=newVertebrate();
vertebrate.spine1=”脊柱”;//public的就能被直接调用Mammalmammal=newMammal();
Fishfish=newFish();
Animalanimal=newAnimal();
Console.WriteLine(“我是一只哺乳动物”);
mammal.Scukle();
animal.Breate();
mammal.Breate();
fish.Breate();
mammal.Sleep();
mammal.Message();
}
}classFish:Vertebrate
{publicoverridevoidBreate()//重写基类中的虚办法{
Console.WriteLine(“用鳃呼吸”);
}
}classAnimal:Vertebrate
{
}classMammal:Vertebrate//派生类:基类{privatestringarms;privatestringlegs;privateintage;publicintAge
{set{age=value;}get{returnage;}
}publicMammal()
{
arms=”前肢”;
legs=”后肢”;
Age=0;
Weigth=10;
Temperature=37;
}publicvoidScukle()
{
Console.WriteLine(“哺乳”);
}publicoverridevoidBreate()
{
Console.WriteLine(“用肺呼吸”);
}publicvoidMessage()
{
Console.WriteLine(“体重:{0}”,Weigth);
Console.WriteLine(“年龄:{0}”,Age);
Console.WriteLine(“体温:{0}”,Temperature);
Console.WriteLine(“我有{0}和{1}”,arms,legs);
}
}
}

未经允许不得转载:IT技术网站 » C#Protected和多态
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

志在指尖 用双手敲打未来

登录/注册IT技术大全

热门IT技术

C#基础入门   SQL server数据库   系统SEO学习教程   WordPress小技巧   WordPress插件   脚本与源码下载