Concepts of Programming Languages

(Sean Pound) #1
12.8 Support for Object-Oriented Programming in C# 557

dynamic. This could cause the problem of object slicing, but this is prevented
by the restriction that structs cannot be subclassed. More details of how C#
structs differ from its classes appear in Chapter 11.

12.8.2 Inheritance


C# uses the syntax of C++ for defining classes. For example,

public class NewClass : ParentClass {... }

A method inherited from the parent class can be replaced in the derived
class by marking its definition in the subclass with new. The new method hides
the method of the same name in the parent class to normal access. However,
the parent class version can still be called by prefixing the call with base. For
example,

base.Draw();

C#’s support for interfaces is the same as that of Java.

12.8.3 Dynamic Binding
To allow dynamic binding of method calls to methods in C#, both the base
method and its corresponding methods in derived classes must be specially
marked. The base class method must be marked with virtual, as in C++. To
make clear the intent of a method in a subclass that has the same name and
protocol as a virtual method in an ancestor class, C# requires that such methods
be marked override if they are to override the parent class virtual method.^9
For example, the C# version of the C++ Shape class that appears in Section
12.5.3 is as follows:

public class Shape {
public virtual void Draw() {... }

...
}
public class Circle : Shape {
public override void Draw() {... }
...
}
public class Rectangle : Shape {
public override void Draw() {... }
...
}
public class Square : Rectangle {
9. Recall that this can be specified in Java with the annotation @Override.

Free download pdf