Object Oriented Programming and C#: Cars Exercise

The following C# program will incorporate many different aspects of object oriented programming into one assignment. The idea is to create one base class and one subclass. Within both of these classes, a method called “DisplayInfo()” is created which will be overwritten for the child class. The three variables within the method are shown at the bottom. Different access modifiers are used to define the scope or range for each variable.

cars

The following code snippet shows the parent class “Cars” with the three variables. The method DisplayInfo() is defined as a virtual method so it can be overridden in the Mercedes class. The Mercedes class inherits the properties from the Cars class. The “base” keyword is used to access the “Cars” class properties. It is important to note that at this point, the price variable cannot be seen within the Mercedes class, so a property must be initialized.

code

The following code allows the price variable to be seen by the child class.

getset

The following code displays the original variables initialized in the base class, then resets the variables to new values and displays those. The “price” variable is showing an error because the property “Price” must be used in its place.

code2

The result:

result

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s