Solution for the Exercise on Inheritance in CSharp
I hope you could solve the exercise.
“As always, it makes sense to solve an exercise for each chapter to examine the learned knowledge.
- Create a main class with the Main method, then a superclass employee with the attributes (variables) lastname, firstname, salary, and the work(), pause().
- Create a subclass Boss with the attribute companycar and the method lead().
- Create another subclass of employee “apprentice” with the attributes workingHours and schoolHours and the method learn();
- Override the method work() of the apprentice class, so that it indicates the working hours of the apprentice.
- Do not forget to create the constructors.
- Create an object from each of the three classes (with arbitrary values) and call the methods lead() of Boss and work() of Azubi.
- Simply print out what the respective coworkers do.
As always, I wish you success and the solution will be in the next lesson.”
My solution:
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Panjutorials { class Program { public static void Main(string[] args) { Employee eMichael = new Employee("Michael", "Müller", 40000); Boss bChuck = new Boss("Porsche", "Norris", "Chuck", 999999999); Apprentice aElton = new Aprentice(80, 30, "Duszat", "Elton", 250000); eMichael.work(); bChuck.lead(); aElton.work(); Console.ReadLine(); } } public class Employee { private string lastname, firstname; private int salary; public Mitarbeiter(string lastname, string firstname, int salary) { this.lastname = lastname; this.firstname = firstname; this.salary = salary; } public void work() { Console.WriteLine("I work!"); } public void pause() { Console.WriteLine("I relax!"); } } public class Boss : Employee { private string companyCar; public Boss(string companyCar, string lastname, string firstname, int salary) : base(lastname, firstname, salary) { this.companyCar = companyCar; } public void lead() { Console.WriteLine("I lead!"); } } public class Apprentice : Employee { private int workingHours, schoolHours; public Azubi(int workingHours, int schoolHours, string lastname, string firstname, int salary) : base(lastname, firstname, salary) { this.workingHours = workingHours; this.schoolHours = schoolHours; } public void study() { Console.WriteLine("I study for " + schoolHours +" hours!"); } public void work() { Console.WriteLine("I work for " + workingHours + " hours!"); } } }