首页 > 学院 > 开发设计 > 正文

【转载】#344

2019-11-17 03:18:27
字体:
来源:转载
供稿:网友

【转载】#344 - Hidden Base Class Member Is Invoked Based on Declared Type of Object

When you use the new modifier to hide a base class method, it will still be called by objects whose type is the base class. Objects whose type is the derived class will call the new method in the derived class.

1 Dog kirby = new Dog("kirby", 15);2 3 // Calls Dog.Bark4 kirby.Bark();5 6 Terrier jack = new Terrier("Jack", 17);7 8 // Calls Terrier.Bark9 jack.Bark();

The Terrier.Bark method is invoked because the variable jack is declared to be of type Terrier.

We could also use a variable of type Dog (the base class) to refer to an instance of a Terrier (the derived class). If we then call the Bark method using this base class variable, the Bark method in the base class is called, even though we're invoking the method on an instance of the derived class.

1 Dog kirby = new Dog("kirby", 15);2 3 // Calls Dog.Bark4 kirby.Bark();5 6 Dog jack = new Terrier("Jack", 17);7 8 // Calls Dog.Bark9 jack.Bark();

原文地址:#344 - Hidden Base Class Member Is Invoked Based on Declared Type of Object


上一篇:【转载】#346

下一篇:【转载】#335

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表