I use C # to write something to play, hit a point object-oriented problem, the code is as follows:
Abstract class Absclass { virtual protected void method () { //do something } public void Domethod () { //do something method (); Do other things } } class Rideclass:absclass { protected void method () { //sub class doing } } class Execute {public void main () { Absclass c = new Rideclass (); C25/>c.domethod (); } }
I would like to call the methods method in the abstract class, and if the inheriting class does not override it, call the method of the abstract class and call the inheriting class if the inheriting class overrides it.
But things tend to backfire, and the result is that the method methods of inheriting classes are not invoked anyway. At this point, if you move the Domethod method into an inherited class (in the case of Rideclass), you can implement my requirements, but this clearly violates the object-oriented intent and is not conducive to later maintenance.
So I went to MSDN and asked about the problem, and it ended up being a perfect solution. In other language platforms it is unclear, at least in the. NET Framework (C # language, other languages just may be different), if you need to use a "derive-inherit" relationship, you must explicitly declare the Virtual-override keyword.
In this example, the Absclass.method method uses the virtual modifier, but the Rideclass.method method does not have the override modifier (without the override modifier, which automatically thinks that the new modifier is used), so in C #, The compiler thinks the method is just a method with the same name as the parent method, and there is no longer any relationship. And in the subclass, the method methods of the parent class are hidden. The so-called "hidden", that is, instantiate an instance of a Rideclass class, which will not be visible in the parent class method methods (in the example, it is not visible, because the access limiter is protected).
So, to implement my initial idea, simply declare override explicitly in the inheriting class.
1 class Rideclass:absclass 2 {3 overrideprotectedvoid method ()4 {5 //Sub class doing6 } 7 }
View Code
. NET inheritance and derivation relationships