2.如果有多个构造函数时:
首先会调用父类的
默认的构造函数,然后在
调用
子类具体的构造函数。
此时Dog(int age)函数为下图所示。
3.若要人为调用基类中的某个具体的构造函数则在Dog(int age)函数修改为:Dog(int age):base(int)
4.两个构造函数之间进行引用时可以把Dog(int age):base(int)改为Dog(int age):this(
) 最后结果为输出表最后三行.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication1Another;
/*实例化对象时,会先调用基类的构造函数,再调用子类的构造函数*/
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Dog dog = new Dog();
dog.age = 10;
dog.Byte();
//抽象函数没有被重写也可以被子类继承
dog.GetAge();
dog.BitMan();
//查看运行结果,得出构造函数由多个组成时的运行顺序检测:
Dog oldDog = new Dog(10);
Console.ReadLine();
}
}
class Animal {
public Animal() {
Console.WriteLine("Animal Constructor!");
}
public Animal(int age) {
Console.WriteLine("Old Animal!");
this.age = age;
}
public int age
{
get;
set;
}
//抽象函数--需要在继承的子类中实现
public virtual void Byte() {
Console.WriteLine("Animal byte!");
}
//不重写也可以被子类继承
public virtual void GetAge() {
Console.WriteLine(age);
}
//不用重写,如果重写的话则在子类中对应的函数需要添加new关键字,否则编译不通过
public void BitMan() {
Console.WriteLine("Animal bite man!");
}
}
//overrade重写Byte()
sealed class Dog : Animal//sealed表示该类无法被继承
{
public Dog() {
Console.WriteLine("Dog Constructor!");
}
public Dog(int age) : this(){
Console.WriteLine("Old Dog!");
this.age = age;
}
public override void Byte()
{
Console.WriteLine("Dog byte!");
}
public new void BitMan() {//new 关键字使得基类中的方法被隐藏。
Console.WriteLine("Dog bit man!");
}
}
}
5.override 与new 的区别。
图片第三行如果不强制转换的话,就会调用父类中的getByte方法
class Program
{
static void Main(string[] args)
{
//子类中用new重写方法,只是把父类中相应的方法隐藏了,而override是重写了基类中相应的方法
Animal dog = new Dog();
dog.Byte();
//dog.BitMan();显示的是父类中的BitMan()方法
((Dog)dog).BitMan();//显示的是子类中的BitMan()方法
}
}