C# Inheritance 👷🏼♂️👷🏼♀️
Java | C# |
---|---|
Super Class | Base Class |
Sub Class | Derived Class |
public class DerivedClass : BaseClass // defining a dervice class
Base Classes
base class constructor
(not implicitly called, as in Java)
public DerivedClass(string name, int a) : BaseClass(name)
{
...
}
base class methods
base.DrawWindow(); // calling a base class method
Or, an overriding method calling the base class method
public override void DrawWindow()
{
base.DrawWindow();
...
}
Method calling in base classes and derived classes
BaseClass dc = new DerivedClass();
dc is declared as a BaseClass (even though it's instantiated as a DerivedClass), so if you call an overriden method in the dc it will call the method from the BaseClass (this is the same as in java)
Abstract Classes
abstract public class Window
{
abstract public void DrawWindow(); // NB. no implemenation (& illegal to add one)
}
public class MyWindow : Window
{
public override void DrawWindow()
{
// implementation goes here
}
}
Sealed Classes
The same as final classes
The Object Class
method | notes |
---|---|
Equals() | |
GetHashCode() | |
GetType() | |
ToString() | |
Finalize() | cleans up non memory resources |
MemberwiseClone() | creates copies of the object - should never be implemented by your type |
ReferenceEquals() | two objects refer to same instance |
// an example of overriding the ToString() method
public override string ToString()
{
return name;
}
Boxing & Unboxing
Boxing is implicit
Unboxing is explicit
int j = (int) o; // Unboxing - can throw InvalidCastException
Nested Classes
public class Fraction
{
private int denominator;
...
internal class FractionDisplay
{
public void Draw(Fraction f) // can reference private members of Fraction, eg. denominator
{
...
}
}
static void Main()
{
Fraction f1 = new Fraction(3,4);
Fraction.FractionDisplay fd = new Fraction.FractionDisplay();
fd.Draw(f1);
}
}
Operator Overloading
- it's common to overload == to indicate if two objects are equal.
- if you overload ==, you must also overload !=
- if you overload >, you must also overload < (and vice versa)
- if you overload >=, you must also overload <= (and vice versa)
If you overload == it is recommended that you overload .Equals(), for example:-
public override bool Equals(object o)
{
if(!(o is Fraction))
{
return false;
}
return this == (Fraction) o;
}
Looks rather like the standard way of overloading the .equals() method in Java.