Looks like no one added any tags here yet for you.
T or F: A class does not always require a constructor, especially if it is static.
True
Constructor —> Describe its function in one short sentence.
Constructors are used to initialize an instance of a class.
(a) What does the term “state” refer to in the context of C# programming?
(b) When does a class have a state?
(a) What does the term “state” refer to in the context of C# programming?
The data (variables & properties) stored in an object, that define its characteristics at a given time.
(b) When does a class have a state?
A class has a state if it contains instance variables (which holds information about the object)
class Car {
public string Model;
public int Speed;
// Constructor initializes state
public Car(string model, int speed) {
this.Model = model;
this.Speed = speed;
}
}
class Program {
static void Main() {
Car myCar = new Car("Toyota", 100);
Console.WriteLine($"Car Model: {myCar.Model}, Speed: {myCar.Speed} km/h");
}
}
Identify the following in the code above:
(a) The two instance variables
(b) The constructor
Does this class have a state? Justify your answer.
(1) Identify the following in the code above:
(a) The two instance variables are ‘model’ (string) & ‘speed’ (int)
These can also be referred to as the ‘state’ of the object Car
(b) The constructor is…
public Car(string model, int speed) {
this.Model = model;
this.Speed = speed;
(2) Does this class have a state? Justify your answer.
Yes this class has a state.
The instance variables ‘model’ & ‘speed’ represent the state of a Car object
class Car {
public string Model; // Instance variable (state)
public int Speed; // Instance variable (state)
// Constructor initializes state
public Car(string model, int speed) {
this.Model = model;
this.Speed = speed;
}
}
class Program {
static void Main() {
Car myCar = new Car("Toyota", 100);
Console.WriteLine($"Car Model: {myCar.Model}, Speed: {myCar.Speed} km/h");
}
}
class Utility {
public static void PrintMessage() {
Console.WriteLine("Hello!");
}
}
class Program {
static void Main() {
Utility.PrintMessage(); // No object creation needed
}
}
Observe the class above and determine the following…
Does the class have a state? Justify your answer.
Do either of the classes use a constructor? Why or why not?
(1) Does the class have a state? Justify your answer.
No
Neither of these class does not store any instance variables (states)
It only has a method
(2) Do either of the classes use a constructor? Why or why not?
No
Since neither of the classes in the code have a state, it does not require a constructor
Is the following statement True or False? Justify your answer.
“If a class only performs actions (methods) without storing any data (state), it does not need a constructor.”
True. The class may not need a constructor because there’s nothing to initialize when creating an object.
Constructor in C#
(a) Define.
(b) Key Characteristics.
(a) Define
Special method that is automatically called when an object of a class is created
Used to initialize objects, set default values, or execute startup logic
(b) Key Characteristics
Same Name as its Class — A constructor must have the same name as the class it belongs to
No Return Type — Unlike regular methods, constructors do not have a return type (not even void
)
Called Automatically — A constructor is invoked (called on) automatically when an object of the class is instantiated
What happens if you don’t explicitly define a constructor for a class?
C# provides a default constructor
T or F: Regular methods in C# must have a return type.
True
T or F: In C#, a constructor must have the same name as the class it belongs to.
True
When is a Class constructor invoked/called on automatically?
When an object of the class is instantiated
Are default constructors parameterized or non-parameterized?
Non-parameterized
What are the major differences b/w parameterized & non-parameterized constructors?
Parameterized Constructor
Can accept parameters to initialize an object with specific values
Typically used to initialize object fields w/ default or predefine values
Automatically provide by C# if no constructor is explicitly defined by the programmer
Example Code
class Car
{
public string Brand;
// Parameterized Constructor
public Car(string brandName)
{
Brand = brandName;
}
}
class Program
{
static void Main()
{
Car myCar = new Car("Toyota");
Console.WriteLine(myCar.Brand); // Output: Toyota
}
}
Non-Parameterized Constructor
Accepts one or more parameters
Allows object properties to be set dynamically at time of object creation
Useful for when different objects need different initial values
T or F: Unlike methods, constructors do not have a return type, except for void
which can be used as a return type for constructors.
False.
Constructors do not have a return type INCLUDING void
.
Read the question commented in the code below.
class WrongExample
{
public void WrongExample() // This is intended to be a constructor, but it isn't. Why? And what is it?
{
}
}
This is not a constructor; it's a method!
This is because
T or F: Constructs almost always have a “Public Access Modifier”
True
T or F: Constructors can be public of private.
True
What syntax is used to create a…
(a) Parameterized Constructor
(b) Non-Parameterized Constructor
(a) Parameterized Constructor Syntax
A constructor that takes one or more parameters.
Allows setting initial values when an object is created.
class ClassName
{
// Parameterized constructor (takes arguments)
public ClassName(string param1, int param2)
{
// Use parameters to initialize properties
}
}
(b) Non-Parameterized Constructor
A constructor with no parameters.
Typically initializes object properties with default values.
class ClassName
{
// Non-parameterized constructor (no arguments)
public ClassName()
{
// Initialization code
}
}
Constructor overloading is used to…
Define multiple constructors (with the same name) with different parameters in the same class
The following sample code demonstrates constructor overloading.
class Car
{
public string Brand;
// Parameterized Constructor
public Car(string brandName)
{
Brand = brandName;
}
}
class Program
{
static void Main()
{
Car myCar = new Car("Toyota");
Console.WriteLine(myCar.Brand); // Output: Toyota
}
}
(a) Explain why this code is a demonstration of constructor overloading.
(b) Describe the differences in properties/characteristics of each constructor.
class Car
{
public string Brand;
public int Year;
// Default Constructor
public Car()
{
Brand = "Unknown";
Year = 0;
}
// Parameterized Constructor
public Car(string brandName, int year)
{
Brand = brandName;
Year = year;
}
}
class Program
{
static void Main()
{
Car car1 = new Car();
Console.WriteLine($"{car1.Brand}, {car1.Year}"); // Output: Unknown, 0
Car car2 = new Car("Ford", 2022);
Console.WriteLine($"{car2.Brand}, {car2.Year}"); // Output: Ford, 2022
}
}
This sample code demonstrates constructor overloading because…
the Car class has multiple constructors that all have the same name (‘Car’), but diff parameters (one class has 1 parameter, the other has 2)
the correct constructor is called based on how the object is instiated
Default Constructor (i.e. Car() )
No parameters
Initializes Brand to “Unknown” and Year to 0
Used when object is created w/o passing any arguments
Car car1 = new Car(); // Calls the default constructor
Parameterized Constructor (i.e. Car(string brandName, int year)
Takes 2 parameters:
String ‘brandName’
Integer ‘year’
Assigns values to both the Brand and Year fields
Used when specific values are provided at the time of object creation
Which type of constructor should you use when creating multiple objects of the same type, but you want them to have different initial values?
Parameterized Constructor
Does the sample code above demonstrate constructor overloading?
If so, provide a brief description of how.
class Car
{
public string Brand;
public int Year;
public Car()
{
Brand = "Unknown";
Year = 0;
}
public Car(string brand, int year)
{
Brand = brand;
Year = year;
}
}
class Program
{
static void Main()
{
Car car1 = new Car();
Car car2 = new Car("Toyota", 2023);
Console.WriteLine($"{car1.Brand}, {car1.Year}");
Console.WriteLine($"{car2.Brand}, {car2.Year}");
}
}
Yes it does demonstrate constructor overloading. See comments in the code below.
class Car
{
public string Brand;
public int Year;
// Default Constructor
public Car()
{
Brand = "Unknown";
Year = 0;
}
// Parameterized Constructor
public Car(string brand, int year)
{
Brand = brand;
Year = year;
}
}
class Program
{
static void Main()
{
Car car1 = new Car(); // Calls the default constructor
Car car2 = new Car("Toyota", 2023); // Calls the parameterized constructor
Console.WriteLine($"{car1.Brand}, {car1.Year}"); // Output: Unknown, 0
Console.WriteLine($"{car2.Brand}, {car2.Year}"); // Output: Toyota, 2023
}
}
Does the sample code above demonstrate constructor overloading?
If so, provide a brief description of how.
class Person
{
public string Name;
public int Age;
public Person()
{
Name = "Not Provided";
Age = 0;
}
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
class Program
{
static void Main()
{
Person p1 = new Person();
Person p2 = new Person("Alice", 25);
Console.WriteLine($"{p1.Name}, {p1.Age}");
Console.WriteLine($"{p2.Name}, {p2.Age}");
}
}
Yes it does demonstrate constructor overloading. See comments in the code below.
class Person
{
public string Name;
public int Age;
// Default Constructor
public Person()
{
Name = "Not Provided";
Age = 0;
}
// Parameterized Constructor
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
class Program
{
static void Main()
{
Person p1 = new Person(); // Calls the default constructor
Person p2 = new Person("Alice", 25); // Calls the parameterized constructor
Console.WriteLine($"{p1.Name}, {p1.Age}"); // Output: Not Provided, 0
Console.WriteLine($"{p2.Name}, {p2.Age}"); // Output: Alice, 25
}
}
Does the sample code above demonstrate constructor overloading?
If so, provide a brief description of how.
class Animal
{
public string Type;
public Animal()
{
Type = "Unknown";
}
}
class Program
{
static void Main()
{
Animal a1 = new Animal();
Console.WriteLine(a1.Type); // Output: Unknown
}
}
No this code does not demonstrate constructor overloading.
class Animal
{
public string Type;
// Only one constructor (no overloading)
public Animal()
{
Type = "Unknown";
}
}
class Program
{
static void Main()
{
Animal a1 = new Animal();
Console.WriteLine(a1.Type); // Output: Unknown
}
}
Does the sample code above demonstrate constructor overloading?
If so, provide a brief description of how.
class Book
{
public string Title;
// Only one constructor (no overloading)
public Book(string title)
{
Title = title;
}
}
class Program
{
static void Main()
{
Book b1 = new Book("C# Programming");
Console.WriteLine(b1.Title); // Output: C# Programming
}
}
No this code does not demonstrate constructor overloading.
class Book
{
public string Title;
// Only one constructor (no overloading)
public Book(string title)
{
Title = title;
}
}
class Program
{
static void Main()
{
Book b1 = new Book("C# Programming");
Console.WriteLine(b1.Title); // Output: C# Programming
}
}
Demonstrate the syntax used to create a non-parameterized constructor
(a) Define “Access Modifier”
(b) What is the difference b/w a public & a private access modifier”
(c) Name two other commonly used examples of access modifiers (besides public & private)
(a) Define “Access Modifier”
C# keyword
Defines visibility & accessibility of a class, method or variable
Controls parts of a program that can access or modify a particular piece of code
(b) What is the difference b/w a public & a private access modifier
Public access modifier —> allows a variable, method, or class can be accessed from anywhere in the program
Private access modifier —> restricts access/use of the modifier (i.e. element) within the class it belongs to
(c) Other commonly used access modifiers
public
private
protected
internal
protected internal
What is the difference b/w Public & Private Access Modifiers?
Feature | public | private |
---|---|---|
Accessibility | Anywhere in the program | Only within the same class |
Used For | Members that should be accessible everywhere | Encapsulated data or internal logic |
Example Usage | Class methods, properties, and constructors | Helper methods, internal logic, sensitive data |
T or F: Encapsulation & Data Hiding are the same thing.
False.
Encapsulation
(a) Define
(b) Purpose
(c) Explain how its achieved through code.
(a) Define
Process of bundling data (variables) & methods (functions) that operate on the data into a single unit (a class)
(b) Purpose
To keep an object’s internal data safe from unintended changes by limiting direct access.
(c) Explain how its achieved through code.
Implemented using access modifiers like private
, public
, protected
Data Hiding
(a) Define
(b) Purpose
(c) How is it achieved in coding?
(a) Define
Restricts direct access to an object’s internal details to prevent misuse.
(b) Purpose
Protects sensitive information from being accessed and modified without authorization.
(c) How is it achieved in coding?
Achieved by making variables private
or protected
.
Example Demonstrating public vs. private
class Person
{
public string Name; // Public: Accessible from anywhere
private int age; // Private: Only accessible within this class
// Public method (can be called from outside the class)
public void SetAge(int newAge)
{
age = newAge; // Allowed (accessing private field within the same class)
}
// Public method to display age
public void DisplayAge()
{
Console.WriteLine($"Age: {age}"); // Allowed
}
}
class Program
{
static void Main()
{
Person p = new Person();
p.Name = "Alice"; // ✅ Allowed (public member)
// p.age = 25; // ❌ Not allowed (private member, cannot be accessed directly)
p.SetAge(25); // ✅ Allowed (indirectly modifying private field through a public method)
p.DisplayAge(); // Output: Age: 25
}
}
Name the benefits of encapsulation & data hiding.
Making elements private prevents direct access and modification, maintaining data integrity.
Public methods allow controlled access to private data members.
Data hiding is not foolproof but helps prevent accidental modifications.
this
keyword
Refers to the current object instance
Distinguishes instance variables from local variables or parameters with the same name
What is the difference b/w static & instance classes?
Static Classes —> Cannot have instance members and does not need a constructor.
Instance Classes —> require constructors and instance methods.
Garbage Collector (GC)
(a) What is it?
(b) How does it work?
(a) What is it?
Automatic memory management feature that removes unused objects from memory to free up space & improve program/computer performance
Automatic —> meaning it runs automatically in the background all the time
(b) How does it work?
The GC scans & identifies objects in memory that are no longer in use — meaning these objects have no references pointing to them (i.e. no pointers)
The GC runs automatically & deletes unused objects, which frees up memory
GC automatically reclaims memory occupied by unreferenced objects
Objects are removed when a program ends, freeing memory.
Manual memory management can be used instead of relying on the GC.
T or F: It is rarely necessary to use the GC and its recommended to not use unless completely necessary.
True
Which method & what syntax is used to explicitly force GC to occur?
Method used for explicit GC —> GC.Collect( ):
Example:
GC.Collect(); // Forces garbage collection
GC.WaitForPendingFinalizers(); // Waits until cleanup is done
Name one simple/basic example where GC may be used.
In freeing up space when a device/program is in low-memory conditions.
For what reasons would you make a string private?
To encapsulate/data hide, which protects data from being accessed by unauthorized personnel.
If you have a class state with 5 variables and a 3-parameter constructor, then how many of the variables must be set/declared within the class itself?
2 of the variables must be declared/set within the class itself since they are not declared w/in the class’ constructor.
Name the 2 ways in which computer memory space can be freed up by altering a progrgam?
Using the automatic built-in Garbage Collector
Manually triggering Garbage Collection
Every single class inherits from the ______ class.
Every single class inherits from the object class.
***EXAM QUESTION
T or F: Abstraction and Abstract Classes are the same thing.
False.
Abstraction and Abstract Classes are NOT the same thing.
They are completely different, although both are parts of OOP.
***FINAL EXAM QUESTION
Name the 4 Pillars of OOP
Inheritance
Interfaces
Abstract Classes
Polymorphism
Inheritance
(a) Define
(b) What rule must all child classes of a parent class follow
(a) Define
A child class inherits all the variables & methods that are in its parent classes
(b) What rule must all child classes of a parent class follow (hint: think methods)
A child class must specialize/differ from its parent class in some way (i.e. have additional variables or methods)
Define & demonstrate each of the following with a sketch.
(a) Multiple Inheritance
(b) Multi-Level Inheritance
(c) Hierarchical Inheritance
(a) Multiple Inheritance
A class that belongs to more than one parent class
(b) Multi-Level Inheritance
A class that is derived from another derived class
Class A is derived from Class B
Class B is derived from Class C
Therefore, Class A is a “grandchild” of Class C
(c) Hierarchical Inheritance
Multiple subclasses inherit from the same base class
Which of the following is and is NOT permitted in the following languages: C++, C#, Java.
(a) Multiple Inheritance
(b) Multi-Level Inheritance
(c) Hierarchical Inheritance
(a) Multiple Inheritance
Yes
C++
No
C#
Java
(b) Multi-Level Inheritance
Allowed in all (C++, C# & Java)
(c) Hierarchical Inheritance
Allowed in all (C++, C# & Java)
In Inheritance/UML diagrams, the direction an arrow points represents…
Where a class is derived from.
What is Polymorphism?
A method can accept both a parent class and its derived classes.
What is the opposite of polymorphism?
The opposite of polymorphism is restricting methods to accept only the parent class using sealed
.
Compare & Contrast Interfaces & Abstract Classes
Feature | Abstract Class | Interface |
---|---|---|
Contains instance variables | Yes | No |
Abstract methods | Yes | Yes |
Concrete methods | Yes | No |
Multiple inheritance | No | Yes |
What is Visual Paradigm?
A UML modelling tool used for creating diagrams to represent class relationships.
class Car
{
private string brand;
public void SetBrand(string carBrand)
{
brand = carBrand;
}
public string GetBrand()
{
return brand;
}
}
class Program
{
static void Main()
{
Car myCar = new Car();
myCar.SetBrand("Toyota");
Console.WriteLine(myCar.GetBrand());
}
}
How is encapsulation used in the code sample above? Be specific.
See the comments in the sample code below for answer:
class Car
{
private string brand; // Private variable
// Public method to set data
public void SetBrand(string carBrand)
{
brand = carBrand;
}
// Public method to get data
public string GetBrand()
{
return brand;
}
}
class Program
{
static void Main()
{
Car myCar = new Car();
myCar.SetBrand("Toyota"); // Allowed (using method)
Console.WriteLine(myCar.GetBrand()); // Output: Toyota
}
}
class BankAccount
{
private double balance;
public BankAccount(double initialBalance)
{
balance = initialBalance;
}
public void Deposit(double amount)
{
if (amount > 0)
balance += amount;
}
public double GetBalance()
{
return balance;
}
}
class Program
{
static void Main()
{
BankAccount account = new BankAccount(1000);
account.Deposit(500);
Console.WriteLine($"Balance: {account.GetBalance()}");
}
}
How is data hiding used in the code sample above? Be specific.
See the comments in the sample code below for answer.
class BankAccount
{
private double balance; // Private variable
public BankAccount(double initialBalance)
{
balance = initialBalance;
}
// Method to deposit money
public void Deposit(double amount)
{
if (amount > 0)
balance += amount;
}
// Method to get the balance
public double GetBalance()
{
return balance; // Can only view balance, not modify directly
}
}
class Program
{
static void Main()
{
BankAccount account = new BankAccount(1000);
account.Deposit(500);
Console.WriteLine($"Balance: {account.GetBalance()}"); // Output: Balance: 1500
}
}
(a) What is an Interface?
(b) What is the major rule when using an interface?
©
(a) What is an Interface?
A blueprint that defines a collection of method signatures that a class can implement
Specifies what methods a class will have and how they should work
(b) What is the major rule when using an interface?
When using an interface — you must provide an implementation for each method defined in the interface within the implementing class.
using System;
interface IVehicle
{
void StartEngine(); // Method signature
void StopEngine(); // Method signature
}
class Car : IVehicle
{
public void StartEngine()
{
Console.WriteLine("Car engine started.");
}
public void StopEngine()
{
Console.WriteLine("Car engine stopped.");
}
}
class Motorcycle : IVehicle
{
public void StartEngine()
{
Console.WriteLine("Motorcycle engine started.");
}
public void StopEngine()
{
Console.WriteLine("Motorcycle engine stopped.");
}
}
class Program
{
static void Main()
{
IVehicle myCar = new Car();
myCar.StartEngine(); // Output: Car engine started.
myCar.StopEngine(); // Output: Car engine stopped.
IVehicle myMotorcycle = new Motorcycle();
myMotorcycle.StartEngine(); // Output: Motorcycle engine started.
myMotorcycle.StopEngine(); // Output: Motorcycle engine stopped.
}
}
(a) Identify the interface and method signatures in the code above.
(b) What output will be produced from this code?
(c) Describe how the classes are implemented.
(a) Identify the interface and method signatures in the code above.
IVehivle
is the interface. It defines the method signatfures StartEngine
and StopEngine
(b) What output will be produced from this code?
class Program
{
static void Main()
{
IVehicle myCar = new Car();
myCar.StartEngine(); // Output: Car engine started.
myCar.StopEngine(); // Output: Car engine stopped.
IVehicle myMotorcycle = new Motorcycle();
myMotorcycle.StartEngine(); // Output: Motorcycle engine started.
myMotorcycle.StopEngine(); // Output: Motorcycle engine stopped.
}
}
(c) Describe how the classes are implemented.
The Car
and Motorcycle
classes implement this interface by providing their own definitions of these methods.
The Program
class demonstrates creating instances of Car
and Motorcycle
and calling methods defined in the interface.
When is it best to use properties rather than private fields? How about the vice versa?
Use properties (public string Make { get; }
) when you want controlled access (like read-only properties).
Use private fields (private string make;
) if you just need to store data internally.
Properties and private fields are two different ways to…
Properties and private fields are two different ways to… declare instance variables that will be used in a constructor.