What is it really?
Problem
Only some of them can charge
A company has a fleet of regular and electric cars. Every evening the electric ones need to be charged. ElectricCar inherits from Car and adds Charge(), so they are all in one Car[] array:
Car[] fleet ={ new Car("Skoda"), new ElectricCar("Tesla", 35), new Car("Dacia"), new ElectricCar("Nissan", 60)};foreach (Car c in fleet){ c.Charge();}The program does not compile:
"'Car' does not contain a definition for 'Charge'".
You know why from the lesson on polymorphism: the type of the variable decides what you can call. c is a Car, and Car has no charging.
A regular car really cannot be charged. You have to ask each car: "are you electric?"
The idea
Ask the object what it is
foreach (Car c in fleet){ if (c is ElectricCar e) { e.Charge(); Console.WriteLine(e.Brand + ": charged to " + e.Battery + "%"); }}Tesla: charged to 100%Nissan: charged to 100%c is ElectricCar e does two things at once:
- it checks whether the object
cpoints to is anElectricCar; - if it is, it creates a variable
eof typeElectricCarthat points to the same object.
Through e you can now call Charge(). The cars stay the same. You just look at the object through a more specific type.
This is called a type check. Going from the parent type to the child type is called a downcast: down the chain Object → Car → ElectricCar.
e exists only inside the if. Outside it, the object is just a Car again.
foreach (Car c in fleet){ if (c is ElectricCar e) { e.Charge(); Console.WriteLine(e.Brand + ": charged to " + e.Battery + "%"); }}Step by step, in words
- fleet is an array of Car: 2 regular and 2 electric cars.
- c points to Skoda: is says "no". The body of the if is skipped.
- c points to Tesla: is says "yes". e is a second arrow to the same car, and it charges it.
- c points to Dacia: is says "no". The body of the if is skipped.
- c points to Nissan: is says "yes". e is a second arrow to the same car, and it charges it.
- The cars do not change. The check only looks at the object through a more specific type.
Try it
Is it a car?
What will the program print?
Car c = new ElectricCar("Tesla", 35);Car d = new Car("Skoda");Console.WriteLine(c is Car);Console.WriteLine(c is ElectricCar);Console.WriteLine(d is ElectricCar);An electric car is also a car, so the first check is true. The check does not ask "is it exactly a Car?" but "can this object be used as a Car?". The regular car d is not electric, so the last check is false.
The idea
Other forms you will run into
Besides is there is also as. It tries the conversion, and if the object is not of that type, it gives null instead of an error:
ElectricCar e = fleet[1] as ElectricCar;if (e != null){ e.Charge(); Console.WriteLine(e.Brand + ": " + e.Battery + "%");}ElectricCar none = fleet[0] as ElectricCar;Console.WriteLine(none == null);Tesla: 100%Truefleet[0] is "Skoda", so as gives null. Then you have to check for null before you call methods. With is ElectricCar e the check and the conversion are in one place, so it is shorter.
More precisely, if you are curious
- The classic cast
(ElectricCar)cexists too. If the object is not anElectricCar, the program stops withInvalidCastException. - The check is always false for
null:null is Carisfalse. So after a successfulisyou never havenull.
- The check works with interfaces too:
a is ISwimmable sasks whether the object's class implements the contract.
Try it
Find the bug
The program counts the regular and the electric cars. The fleet has two of each, but it prints:
Regular: 4, electric: 0Which line is the bug on?
Pick the line with the bug.
Every electric car is also a Car, so the first check is true for all four cars. The program never gets to the second one. Check the more specific type first: if it is an ElectricCar, count it as electric, otherwise as regular.
The idea
A check or a method?
You want to print what each car runs on. A type check can do it:
foreach (Car c in fleet){ if (c is ElectricCar) { Console.WriteLine(c.Brand + ": electricity"); } else { Console.WriteLine(c.Brand + ": gasoline"); }}But this is the salary with an if per role from the lesson on polymorphism. Every car has an energy source, just a different one. That is a job for a method in Car, overridden in ElectricCar:
// in Carpublic virtual string Energy(){ return "gasoline";}
// in ElectricCarpublic override string Energy(){ return "electricity";}foreach (Car c in fleet){ Console.WriteLine(c.Brand + ": " + c.Energy());}Skoda: gasolineTesla: electricityDacia: gasolineNissan: electricityTomorrow a hybrid car comes along. With the method, you write a new class. With the checks, you hunt down every if in the program.
The rule:
- Every object does it, each in its own way: a method in the parent, and overriding.
- Only some objects can do it (charging, pedaling): a type check.
Try it
What is missing?
foreach (Car c in fleet)
{
if (c ElectricCar e)
{
e.Charge();
}
}is: it checks the type and, if it matches, creates e.In short
The four pillars of OOP
With this lesson you have finished the modules "Classes and objects" and "Inheritance and polymorphism". Object-oriented programming rests on four ideas. You already use all of them:
- Encapsulation. The object's data is hidden, and from outside you reach it only through methods that guard the rules.
Accountkeeps the balance private and offers onlyDeposit()andWithdraw(). Encapsulation - Inheritance. What is shared sits in one place, the parent, and the child adds its own.
Manageris anEmployeewith a bonus. Inheritance - Polymorphism. One call, different behavior depending on the object.
e.MonthlyPay()in one loop works out the pay of an employee, a manager and an intern. Polymorphism - Abstraction. You say what the object must be able to do, and each class decides how. The abstract
Shapepromises an area, the IPayable interface promises an amount to pay. Abstract classes, Interfaces
Exercise
What is it really?
Solve these in your editor.
1. Parking lot. A SimpleCar[] array of regular and family cars (FamilyCar inherits from SimpleCar). For each one, print its type. Watch the order of the checks.
This is a SimpleCarThis is a FamilyCarThis is a SimpleCar2. Dances. A DanceMove[] array of regular and breakdance moves. For the breakdance moves, also print the complexity. For that you need the variable from the check.
moonwalk: DanceMovewindmill: BreakDanceMove, complexity 8salsa: DanceMove3. Fleet. Take Car and ElectricCar from the exercise in the "Inheritance" lesson. In a Car[] array, put a "Skoda" with 40 L, a "Tesla" with efficiency 5, a "Dacia" with 5 L and a "Nissan" with efficiency 4. Each one drives 100 km: the electric ones with DriveElectric, the rest with Drive. Then print the kilometers and the fuel or the battery.
Skoda: 100 km, fuel 30 LTesla: 100 km, battery 80%Not enough fuel for 100 kmDacia: 0 km, fuel 5 LNissan: 100 km, battery 75%4. Zoo. An abstract class Animal with Sound(), and child classes Cat, Dog and Fish. Only Fish implements ISwimmable with Swim(). In a loop over the animals, call each one's sound, and for the ones that can swim, also call Swim().
Meow, meow!Woof, woof!The fish is silent.The fish swims.More tasks
- Pedals. In the exercise from the "Abstract classes" lesson,
garage[1].Pedal()did not compile. Fix it with a type check: in the loop overVehicle[], every vehicle starts, and the bicycle also pedals. - Payments by kind. From the "Interfaces" lesson: the IPayable[] array holds employees and invoices. Print the total for salaries and the total for invoices separately. For Ivan, Maria and the two invoices: €5,500 in salaries and €2,140 in invoices.
Test