Instantiating the Class
Although we have not explicitly added any functionality to the class, it can now be instantiated to create objects. These objects will have the standard behaviour of all classes. To demonstrated this, return to the program code file containing the Main method. In this method we will create a new vehicle object and run its ToString method to see the results. As we have not yet defined how ToString should work, this will simply show the fully qualified name.static void Main(string[] args) { Vehicle car = new Vehicle(); Console.WriteLine(car.ToString()); // Outputs "ClassTest.Vehicle" }
Adding Methods
Public Methods
Public methods are part of the class' public interface, ie. these are the methods that can be called by other objects.- C# Methods
- C# Functional Methods
- C# Method Parameters
public void PressHorn() { Console.WriteLine("Toot toot!"); }
static void Main(string[] args) { Vehicle car = new Vehicle(); car.PressHorn(); // Outputs "Toot toot!" }
Private Methods
To provide for encapsulation, where the internal functionality of the class is hidden, some methods will be defined as private. Methods with a private protection level are completely invisible to external classes. This makes it safe for the code to be modified to change functionality, improve performance, etc. without the need to update classes that use the public interface. To define a method as private, the private keyword can be used as a prefix to the method. Alternatively, using no prefix at all implies that the method is private by default.The following method of the car class is a part of the internal implementation not the public interface so is defined as being private.
private void MonitorOilTemperature() { // Internal oil temperature monitoring code...; }
static void Main(string[] args) { Vehicle car = new Vehicle(); car.MonitorOilTemperature(); }
No comments:
Post a Comment