class Shape
{
public virtual void Draw()
{
Console.WriteLine("Shape.Draw") ;
}
}class Rectangle : Shape
{
public new void Draw()
{
Console.WriteLine("Rectangle.Draw");
}
}
class Square : Rectangle
{
//这里不用 override
public new void Draw()
{
Console.WriteLine("Square.Draw");
}
}
class MainClass
{
static void Main(string[] args)
{
Console.WriteLine("Using Polymorphism:");
Shape[] shp = new Shape[3];
Rectangle rect = new Rectangle();
shp[0] = new Shape();
shp[1] = rect;
shp[2] = new Square();
shp[0].Draw();
shp[1].Draw();
shp[2].Draw();
Console.WriteLine("Using without Polymorphism:");
rect.Draw();
Square sqr = new Square();
sqr.Draw();
}
}
Output:
Using Polymorphism
Shape.Draw
Shape.Draw
Shape.Draw
Using without Polymorphism:
Rectangle.Draw
Square.Draw
上面的代码中我有一个问题不太明白:
shp[0] = new Shape();
shp[1] = rect;
shp[2] = new Square();
shp[0].Draw();
shp[1].Draw();
shp[2].Draw();
和
rect.Draw();
Square sqr = new Square();
sqr.Draw();
都是先通过实例化对象后调用,这两个有什么区别?不是说隐藏后的基类方法只能通过基类访问调用吗?
小弟初学,还望各位大侠帮忙帮我解释解释!在此先谢过!
{
public virtual void Draw()
{
Console.WriteLine("Shape.Draw") ;
}
}class Rectangle : Shape
{
public new void Draw()
{
Console.WriteLine("Rectangle.Draw");
}
}
class Square : Rectangle
{
//这里不用 override
public new void Draw()
{
Console.WriteLine("Square.Draw");
}
}
class MainClass
{
static void Main(string[] args)
{
Console.WriteLine("Using Polymorphism:");
Shape[] shp = new Shape[3];
Rectangle rect = new Rectangle();
shp[0] = new Shape();
shp[1] = rect;
shp[2] = new Square();
shp[0].Draw();
shp[1].Draw();
shp[2].Draw();
Console.WriteLine("Using without Polymorphism:");
rect.Draw();
Square sqr = new Square();
sqr.Draw();
}
}
Output:
Using Polymorphism
Shape.Draw
Shape.Draw
Shape.Draw
Using without Polymorphism:
Rectangle.Draw
Square.Draw
上面的代码中我有一个问题不太明白:
shp[0] = new Shape();
shp[1] = rect;
shp[2] = new Square();
shp[0].Draw();
shp[1].Draw();
shp[2].Draw();
和
rect.Draw();
Square sqr = new Square();
sqr.Draw();
都是先通过实例化对象后调用,这两个有什么区别?不是说隐藏后的基类方法只能通过基类访问调用吗?
小弟初学,还望各位大侠帮忙帮我解释解释!在此先谢过!
Square sqr = new Square();
sqr.Draw();
子类的引用,并用自己的实例初始化,并且这两个类都有自己的实现shp[0] = new Shape();
shp[1] = rect;
shp[2] = new Square();
shp[0].Draw();
shp[1].Draw();
shp[2].Draw();
shp是父类Shape的引用,用子类实现,子类方法没有overide,而用new,因此调用父类的Draw不知道对不对,个人看法~
shp[1] = rect;
shp[2] = new Square();
shp[0].Draw();
shp[1].Draw();
shp[2].Draw();
是因为你的Shape[] shp = new Shape[3]; 这句,声明了一个数组Shape,有三个元素,但是还没有建立对象啊,所有需要建立三个对象
就有了shp[0] = new Shape();
shp[1] = rect;
shp[2] = new Square();
中间的那句是把已经存在的对象Rectangle rect = new Rectangle(); 赋值给Shape数组的shp[1]这个元素,其他两个是新创建的对象
shp[0].Draw();
shp[1].Draw();
shp[2].Draw();
是调用对象的draw方法啊
本来,如果没有用new关键字,而是用override,则
shp[1]、shp[2]指向的对象都是子类的对象,因此会调用子类的Draw()方法;但是由于用了new关键字,因此,shp[i]就
只看得到Shape类的Draw方法,所以,shp[0]、shp[1]、shp[2]调用的都是Shape类的Draw()方法。