Note that the constructor of the derived class implicitly invokes the constructor of the base class (or superclass in Java terminology). In inheritance, all base class constructors are called before the constructor of a derived class, in the order in which these classes appear in the class hierarchy.
Cast type to base class
As in Java, we cannot use a reference to a base class to access the members and methods of a derived class, even if the base class reference might contain valid references to derived type objects.
We can reference derived classes by implicitly referencing derived types:
ColorPoint clrpt = new ColorPoint();
Point pt = clrpt;
In this code, the base class references a copy of the PT containing the CLRPT reference.
Base keyword
By using the base keyword, we can access the members of the base class in the subclass, even if the base class members are overridden in the superclass. For example, we can create a derived class that contains a method that has the same signature as the base class. If we add the New keyword before this method, it means that this is a new method that belongs to the derived class. With the base keyword, we can still provide methods to access the original methods in the base class.
For example, our point base class is known as the Invert () method, which swaps x and y coordinates. By using code such as the following, we can provide an alternative to this method in the derived class ColorPoint:
public new void invert()
{
int holding = X;
X = Y;
Y = holding;
screenColor = Color.Gray;
}
As you can see, this method swaps x and Y, and then sets the color of the point to Gray. By creating another method in ColorPoint (for example, the following method), we can provide access to the base implementation of this method:
public void baseInvert()
{
base.invert();
}
We can then invoke the base method in the ColorPoint object by calling the Baseinvert () method.
ColorPoint clrpt = new ColorPoint (); Clrpt.baseinvert ();
Keep in mind that if we assign a reference to a base class to an instance of ColorPoint and then access its methods, we will get the same effect:
Point pt = clrpt;
pt.invert();
选择构造函数
基类对象总是在任何派生类之前构造的。因此基类的构造函数在派生类的构造函数之前执行。如果基类有多个构造函数,派生类就可以决定要调用的构造函数。例如,我们可以修改我们的 Point 类来添加第二个构造函数:
public class Point
{
private int x, y;
public Point()
{
x = 0; y = 0;
}
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
}