继承和多态实属一脉相承的两个概念,讲一点我的理解!
继承可能是OO语言中最强有力的工具之一,派生类要比非继承的类更为简洁,通过继承我们可以大量减少代码冗余量。
1,最简单的继承是只继承基类中的一些成员方法和属性,由于成员方法和和属性的代码在基类中已经实现所以就可以不用重复编写;
2,重写基类的Print方法实现自己的功能;
3,函数重载也是多态的一种;
4,由于C#是单继承,也就是一个类不可以从两个或两个以上的类中派生,但是可以从多个接口派生,从而实现C++的多重继承功能;
5,想要定义对象容器可以定义类似于
List<Person> list=new List<Person>();
或
List<IStudent> list=new List<IStudent>;
示例代码如下:
class Person
{
private string _name;
private int _age;
public Person(string name,int age)
{
Name=name;
Age=age;
}
public Person()
{
}
public string Name
{
set{
_name=value;
}
get{
return _name;
}
}
public int Age
{
set{
_age=value;
}
get{
return _age;
}
}
public virtual void Print()
{
Console.WriteLine("I'm {0},{1} yeas old!",Name,Age);
}
}
class Student :Person
{
private int _grade;
private string _number;
public int Grade{
set{
if(value<5&&value>0)
_grade=value;
else
_grade=1;
}
get{
return _grade;
}
}
public string Number
{
set{
if(value.Length!=6)
_number="000000";
else
_number=value;
}
get
{
return _number;
}
}
public Student(string name,int age,int grade,string number) :base(name,age)
{
Grade=grade;
Number=number;
}
public override void Print()
{
base.Print();
Console.WriteLine("I'm a {0} grade student!",Grade);
}
}
interface IStudent
{
void Graduate();
}
class Bachelor:Student,IStudent
{
public Bachelor(string name,int age,int grade,string number):base(name,age,grade,number)
{
}
public void Graduate()
{
Console.WriteLine("Bachelors graduated!");
}
}
class Master:Student,IStudent
{
public Master(string name,int age,int grade,string number):base(name,age,grade,number)
{
}
public void Graduate()
{
Console.WriteLine("Masters graduated!");
}
}
{
private string _name;
private int _age;
public Person(string name,int age)
{
Name=name;
Age=age;
}
public Person()
{
}
public string Name
{
set{
_name=value;
}
get{
return _name;
}
}
public int Age
{
set{
_age=value;
}
get{
return _age;
}
}
public virtual void Print()
{
Console.WriteLine("I'm {0},{1} yeas old!",Name,Age);
}
}
class Student :Person
{
private int _grade;
private string _number;
public int Grade{
set{
if(value<5&&value>0)
_grade=value;
else
_grade=1;
}
get{
return _grade;
}
}
public string Number
{
set{
if(value.Length!=6)
_number="000000";
else
_number=value;
}
get
{
return _number;
}
}
public Student(string name,int age,int grade,string number) :base(name,age)
{
Grade=grade;
Number=number;
}
public override void Print()
{
base.Print();
Console.WriteLine("I'm a {0} grade student!",Grade);
}
}
interface IStudent
{
void Graduate();
}
class Bachelor:Student,IStudent
{
public Bachelor(string name,int age,int grade,string number):base(name,age,grade,number)
{
}
public void Graduate()
{
Console.WriteLine("Bachelors graduated!");
}
}
class Master:Student,IStudent
{
public Master(string name,int age,int grade,string number):base(name,age,grade,number)
{
}
public void Graduate()
{
Console.WriteLine("Masters graduated!");
}
}