Exercise Solutions: Inheritance¶
Line numbers are for reference. They may not match your code exactly.
Class Design¶
This is one example of how 1 base class (Computer
) and 2 derived classes (Laptop
& Smartphone
) can use inheritance.
Using the diagram above, set up the base class:
Computer
.
Testing the
Computer
class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public class Computer
{
public double Ram { get; set; }
public double Storage { get; set; }
public readonly bool hasKeyboard;
public Computer(double ram, double storage, bool hasKeyboard)
{
Ram = ram;
Storage = storage;
this.hasKeyboard = hasKeyboard;
}
public double IncreaseRam(double extraRam)
{
return Ram += extraRam;
}
public double IncreaseStorage(double extraStorage)
{
return Storage += extraStorage;
}
}
|
Use inheritance to create the
Laptop
derived class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public class Laptop : Computer
{
public double Weight { get; set; }
public Laptop(double ram, double storage, bool hasKeyboard, double weight) : base(ram, storage, hasKeyboard)
{
Weight = weight;
}
public bool IsClunky()
{
if (Weight > 5.0)
{
return true;
}
else
{
return false;
}
}
}
|
Class Implementation¶
Add a new MSTest project to your solution.
1 2 3 4 5 6 7 8 9 | // one Computer class tests in the Computer Class
[TestMethod]
public void TestIncreasingRam()
{
Computer testingComputer = new Computer(2, 3, true);
Assert.AreEqual(2, testingComputer.Ram);
testingComputer.IncreaseRam(3);
Assert.AreEqual(5, testingComputer.Ram);
}
|
Try to add three MSTest tests to each class. Consider testing each method or field.
Testing the
Smartphone
class
1 2 3 4 5 6 7 8 | //Smartphone Class
[TestMethod]
public void TestTakingSelfies()
{
SmartPhone testingSmartphone = new SmartPhone(2, 3, true, 800);
testingSmartphone.TakeSelfie();
Assert.AreEqual(801, testingSmartphone.NumberOfSelfies);
}
|
Abstract class design¶
Create the
AbstractEntity
Class.
1 2 3 4 5 6 7 8 9 10 11 12 | // AbstractEntity Class
public class AbstractEntity
{
public int Id { get; set; }
private static int nextId = 1;
public AbstractEntity()
{
Id = nextId;
nextId++;
}
}
|
Update the
Computer
class. RememberComputer
extendsAbstractEntity
.
public class Computer : AbstractEntity
Testing AbstractEntity
using MSTest:
Testing the
Computer
Class
1 2 3 4 5 6 7 8 9 10 | //Computer Class
[TestMethod]
public void TestInheritsId()
{
Computer testingComputer = new Computer(2, 3, true);
Assert.AreEqual(1, testingComputer.Id);
Computer testingComputer2 = new Computer(4, 6, true);
Assert.AreEqual(2, testingComputer2.Id);
}
|
Testing the
Smartphone
class
1 2 3 4 5 6 7 8 | //Smartphone class
[TestMethod]
public void TestInheritingBaseConstructor()
{
SmartPhone testingSmartphone = new SmartPhone(2, 3, true, 800);
Assert.IsNotNull(testingSmartphone.Id);
//...
}
|