可以在类中定义字段和方法,字段为私有,可通过构造方法(写在基类中)控制字段的改变。
方法为私有。
父类中含有构造方法,子类中也需要写构造方法,用于对父类构造方法的调用,其中参数名(父类中定义的字段名),参数类型也需要一致。
类的赋值:
1.父类可以引用子类对象。
2.父类引用只能调用子类继承父类的方法,父类引用不能调用子类独有的方法。
parent newchild = new children1("c11");
newchild.father();
newchild.mother();
Console.WriteLine("newchild 的名字为:"+newchild.getname());
3.子类引用不能直接赋值父类对象,即使将父类对象进行强制转换,也不可以。(编译虽通过,但运行异常)。
定义新类:重定义父类中的方法(并不改变父类中方法体),使用关键字new,但是不使用关键字也可运行,一般不提倡。
//基类:
public void speak() {
Console.WriteLine("This is parent talking");
}
//子类:
new public void speak(){
Console.WriteLine("This is children1 talking");
}
虚基类方法的重写:
//父类:
public virtual void father() {
Console.WriteLine(name+" "+"is my father");
}
//子类:
public override void father(){
Console.WriteLine("Now I'm father");
}
总结:
new是在子类中隐藏父类中同名方法(适用于子类引用自己的对象)。
override是子类重写父类方法,但不会真正的改变基类的方法(适用于父类可以引用子类对象(已用override声明重写方法)的情况,如parent newchild = new children1("c11");及子类(已用override声明重写方法)引用自己的对象的情况)。
定义override方法的注意事项:
1.必须是virtual修饰的方法。
2.要重写的是父类中子类能访问的方法,即public类型 。
多态:
一个方法在不同类中可以有不同的方法体
演示内容:
//基类:
private string name;
public parent(string aname)
{
name = aname;
}
public void speak()
{
Console.WriteLine("This is parent talking");
}
public string getname()
{
return name;
}
public void father() {
Console.WriteLine(name+" "+"is my father");
}
public void mother()
{
Console.WriteLine(name + " " + "is my mother");
}
//子类1:
class children1:parent
{
public children1(string name) : base(name) {
}
new public void speak()
{
Console.WriteLine("This is children1 talking");
}
public void childone() {
Console.WriteLine(getname()+" "+"is children1's move");
}
}
//子类2:
class children2:parent
{
public children2(string name) : base(name) {
}
public void childtwo()
{
Console.WriteLine(getname()+" "+ "is children2's move");
}
}
//主程序:
static void Main(string[] args)
{
parent p = new parent("p");
p.father();
p.mother();
p.speak();
children1 c1 = new children1("c1");
c1.father();
c1.mother();
c1.childone();
c1.speak();
children2 c2 = new children2("c2");
c2.father();
c2.mother();
c2.childtwo();
//类的赋值(父类引用可以直接赋值子类对象)
parent newchild = new children1("c11");
newchild.father();
newchild.mother();
Console.WriteLine("newchild 的名字为:"+newchild.getname());
//以下方法错误(子类引用不能直接赋值父类对象):
//children1 c1child = (children1)new parent("c111");
//c1child.father();
//c1child.mother();
//c1child.childone();
Console.ReadKey();
}