working-with-class-hierarchies-slides
working-with-class-hierarchies-slides
Class Hierarchies
Gill Cleeren
CTO Xpirit Belgium
@gillcleeren
Overview
Adding inheritance
Working with polymorphism
Exploring sealed and abstract classes
Using extension methods
Adding Inheritance
“We have in fact different types of products.
They behave rather similar but based on the
type, they will be differences.
Product
Boxed product
Product
Parent class
Base class
Superclass
Boxed product
Child class
Derived or extended class
Subclass
Product.cs BoxedProduct.cs
Product.cs BoxedProduct.cs
Adding inheritance
Creating the different product classes
Inheritance and Constructors
Product
public BoxedProduct(int id, string name, string? description, Price price, int
maxAmountInStock, int amountPerBox) : base(id, name, description, price,
UnitType.PerBox, maxAmountInStock)
{
AmountPerBox = amountPerBox;
}
}
System.Object
Product
Boxed product
Demo
BoxedProduct Product
Is A
Product p1 = new BoxedProduct();
Product p2 = new FreshProduct();
p1.UseProduct(10);
p2.UseProduct(8);
SaveProduct(boxedProduct);
products[0] = product;
products[1] = boxedProduct;
Product
UseProduct()
P B F P F B P
BoxedProduct
FreshProduct
Adding Polymorphism
Using virtual and override
Product BoxedProduct
Product
Array of Product references
virtual UseProduct()
P P P P P P P
BoxedProduct
override UseProduct()
P B F P F B P
FreshProduct
Actual objects
Demo
product.UseBoxedProduct();//error
Unavailable Methods
public void SaveProduct(Product p)
{
BoxedProduct bp = (BoxedProduct)p;//explicit cast which can be dangerous
if (p is BoxedProduct)
{
}
}
if (bp != null)
{
}
}
while (true)
{
smallestMultiple++;
if (smallestMultiple * AmountPerBox > items)
{
batchSize = smallestMultiple * AmountPerBox;
break;
}
}
base.UseProduct(batchSize);
}
public class Product
{
public virtual void UseProduct(int items)
{
//base implementation
}
}
public class BoxedProduct: Product
{
public void UseProduct(int items)
{
//custom implementation
}
}
Product Program.cs
p1.RemoveProduct();