Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
Course and Project classes


Here is my solution:

using System;

public abstract class Course{      // Abstract class

  private string name;

  public Course(string name){      // ... with constructor
    this.name = name;
  }

  public abstract bool Passed();

}

public class BooleanCourse: Course{   // Inherits from Course

  private bool grade;

  public BooleanCourse(string name, bool grade): base(name){
    this.grade = grade;
  }

  public override bool Passed(){
    return grade;
  }

}

public class GradedCourse: Course{   // Inherits from Course

  private int grade;

  public GradedCourse(string name, int grade): base(name){
    this.grade = grade;
  }  

  public override bool Passed(){
    return grade >= 2;
  }

}

public class Project{

  private Course c1, c2, c3, c4;   // Course is the common type
                                   // of all four variables.

  public Project(Course c1, Course c2, Course c3, Course c4){   // All parameters of type Course
    this.c1 = c1; this.c2 = c2; 
    this.c3 = c3; this.c4 = c4;
  }

  public bool Passed(){
    return 
     (c1.Passed() && c2.Passed() && c3.Passed() && c4.Passed()) ||
     (!(c1.Passed()) && c2.Passed() && c3.Passed() && c4.Passed()) ||
     (c1.Passed() && !(c2.Passed()) && c3.Passed() && c4.Passed()) ||
     (c1.Passed() && c2.Passed() && !(c3.Passed()) && c4.Passed()) ||
     (c1.Passed() && c2.Passed() && c3.Passed() && !(c4.Passed()));
  }

}

public class Program {

  public static void Main(){
    Course c1 = new BooleanCourse("Math", true),          // All variables declared of type Course
           c2 = new BooleanCourse("Geography", true),
           c3 = new GradedCourse("Programming", 0),
           c4 = new GradedCourse("Algorithms", -3);

    Project p = new Project(c1, c2, c3, c4);

    Console.WriteLine("Project Passed: {0}", p.Passed());
  }

}

Please take notice of the comments in the source program.