站内搜索: 请输入搜索关键词
当前页面: 图书首页 > NET For Java Developers Migrating To C#

NET For Java Developers Migrating To C#

[ directory ] Previous Section Next Section

5.7 Summary

Inheritance is a powerful concept and should be used whenever appropriate. However, you should design class hierarchies with caution because C# allows you to extend only one class. Prefer composition over inheritance because composition allows for greater flexibility in switching your actual implementation and insulating the end users of your class from changes to the class's internals.

Here are the key concepts you should take away from this chapter:

  • In C#, methods are nonvirtual by default. In Java, all methods are virtual by default. This means that in C#, virtual dispatching is not automatically turned on; therefore, method calls are always made on the reference instead of the object instantiated. To achieve Java-like virtual dispatching, you must use the virtual and override keywords in the right places.

  • The method parameters and their conversion rules also influence which method gets called at runtime.

  • Subclasses can access the protected and public members of their superclass. Subclasses cannot access the private members of the superclass.

  • A superclass can access all the members of a subclass; that is, this access won't cause a compile-time error. However, the runtime will invoke only the corresponding superclass methods even when the object instantiated and the reference used are those of the subclass.

  • Public and protected static methods can be inherited. Private static methods cannot be inherited.

  • The base keyword can be used to call a superclass method. Only protected and public members can be accessed using the base keyword. A static method cannot use the base keyword.

  • Abstract methods can be contained only in an abstract class. A nonabstract subclass that extends an abstract class must override the corresponding abstract method of the superclass.

  • A base-class reference can be cast to a derived class reference only when the object instantiated is that of the derived class:

    Base b = new Derived();
    ((Derived) b).Test();
    
  • A derived class reference can be cast to any of its superclass references:

    Derived d = new Derived();
    ((Base)d).Test()
    
  • In general, a direct nonvirtual method call on a reference is faster than a virtual call, which in turn is faster than casting. To achieve Java-like automatic virtual dispatching, you should use the virtual or override modifier in C#. Casting should not be used as a substitute for virtual dispatching.

    [ directory ] Previous Section Next Section