Saturday, January 9, 2010

Exception:,Inheritance:

Exception:


The C# language's exception handling features provide a way to deal with any unexpected or exceptional situations that arise while a program is running. Exception

handling uses the try, catch, and finally keywords to attempt actions that may not succeed, to handle failures, and to clean up resources afterwards. Exceptions can be generated by the common language runtime (CLR), by third-party libraries, or by the application code using the throw keyword.
A try block is used by C# programmers to partition code that may be affected by an exception, and catch blocks are used to handle any resulting exceptions.

Within the class we need to add new line “throw new Exception (“ Speed already zero” )” which will be executed when a value less then zero.
Inheritance:
Please refer to the definitions of inheritance discussed in lecture # 1
In order to have a practical solution of inheritance let’s make another class named SportsCar. The class will have similar characteristics of car except that acceleration and braking is faster. Following is code for class SportsCar


The class sports car overrides the accelerate method of class car in other words, of the two accelerate methods present in class SportsCar (one created here and the other one inherited from class car) the method declared in subclass will take precedence.
For this code to work properly “virtual” keyword needs to be appended before each method. Formally speaking, A virtual function is a member function that you expect to be redefined in derived classes. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function.

No comments:

Post a Comment