This concept is often expressed as "one interface, multiple actions". The specific action is determined by the exact nature of circumstances. Once a class has been written, created and debugged, it can be distributed to other programmers for use in their own program. This is called reusability, or in. In OOP, however, inheritance provides an important extension to the idea of reusability. A programmer can use an existing class and without modifying it, add additional features to it.
This simple one-class console "Hello world" program demonstrates many fundamental concepts throughout this article and several future articles. So SimpleHelloWorld is the name of the class that contains the Main method.
On line 1 , a using directive indicates to the compiler that this source file refers to classes and constructs declared within the System namespace.
Line 6 with the public keyword indicates the program accessibility scope for other applications or components. Everything belongs to the class, like fields, properties and methods appear in the class body between the opening and closing braces. The purpose of the Main method is to provide an entry point for application execution. The static keyword in the Main method states that this method would be executed without instantiating the class.
You can compile a C program into either an assembly or a module. If the program has one class that contains a Main method then it can be compiled directly into an assembly. This file has an ". A program with no Main method can be compiled into a module as in the following:. You can then compile this program by F9 or by simply running the C command line compiler csc. Classes are special kinds of templates from which you can create objects. Each object contains data and methods to manipulate and access that data.
The class defines the data and the functionality that each object of that class can contain. A class declaration consists of a class header and body. The class header includes attributes, modifiers, and the class keyword. The class body encapsulates the members of the class, that are the data members and member functions. The syntax of a class declaration is as follows:.
Attributes provide additional context to a class, like adjectives; for example the Serializable attribute. Accessibility is the visibility of the class. The default accessibility of a class is internal. Private is the default accessibility of class members. The following table lists the accessibility keywords;.
Modifiers refine the declaration of a class. The list of all modifiers defined in the table are as follows;. The baselist is the inherited class. By default, classes inherit from the System. Object type. A class can inherit and implement multiple interfaces but doesn't support multiple inheritances. When you open the customer.
The C console application project must require a single entry point Main function that is already generated in the program class. For example if you add a new customer class and want to define one or more Main entry points here then. NET will throw an error of multiple entry points. So it is advisable to delete or exclude the program.
So here in this example the customer class defines fields such as CustID, Name and Address to hold information about a particular customer. It might also define some functionality that acts upon the data stored in these fields. At line 9, we are defining a constructor of the customer class for initializing the class member fields. The constructor is a special function that is automatically called when the customer class object is created instantiated.
And at line 11 we are printing these fields to the console by creating a user defined method displayData. You can then instantiate an object of this class to represent one specific customer, set the field value for that instance and use its functionality, as in:.
Here you use the keyword new to declare the customer class instance. This keyword creates the object and initializes it. When you create an object of the customer class, the. NET framework IDE provides a special feature called Intellisense that provides access to all the class member fields and functions automatically. This feature is invoked when the ".
Normally, as the program grows in size and the code becomes more complex, the Intellisense feature increases the convenience for the programmer by showing all member fields, properties and functions. Sometimes circumstances require multiple classes to be declared in a single namespace. So in that case it is not mandatory to add a separate class to the solution, instead you can attach the new class into the existing program.
Here in this example, we are creating an extra class "demo" in the program. So it doesn't matter how many classes we are defining in a single assembly. Typically, a class will reside entirely in a single file. However, in situations where multiple developers need access to the same class, then having the class in multiple files can be beneficial.
The partial keywords allow a class to span multiple source files. When compiled, the elements of the partial types are combined into a single assembly. In the following example we are adding two files, partialPart1. And finally we are creating an instance of the partialclassDemo in the program. A static class is declared using the "static" keyword. If the class is declared as static then the compiler never creates an instance of the class.
All the member fields, properties and functions must be declared as static and they are accessed by the class name directly not by a class instance object. NET provides the capability of creating libraries components of a base application rather than an executable ". Instead the library project's final build version will be ". DLL" that can be referenced from other outside applications to expose its entire functionality. Then we are implementing a math class library that is responsible of calculating square root and the addition of two numbers as:.
Now create another console based application where you utilize all the class library's functionality. Then you have to add the class library dll file reference to access the declared class in the library dll. Right-click on the Reference then "Add reference" then select the path of the dll file.
When you add the class library reference then you will notice in the Solution Explorer that a new LibraryUtil is added as in the following;. Now add the namespace of the class library file in the console application and create the instance of the class declared in the library as in the following;. A constructor is a specialized function that is used to initialize fields. A constructor has the same name as the class. Instance constructors are invoked with the new operator and can't be called in the same manner as other member functions.
There are some important rules pertaining to constructors as in the following;. Classes with no constructor have an implicit constructor called the default constructor, that is parameterless. The default constructor assigns default values to fields.
A public constructor allows an object to be created in the current assembly or referencing assembly. A constructor can be static. You create a static constructor to initialize static fields. Static constructors are not called explicitly with the new statement. They are called when the class is first referenced.
There are some limitations of the static constructor as in the following;. In the following example the customer class has a static constructor that initializes the static field and this constructor is called when the class is referenced in the Main at line 26 as in the following:.
The purpose of the destructor method is to remove unused objects and resources. Destructors are not called directly in the source code but during garbage collection.
Garbage collection is nondeterministic. A destructor is invoked at an undetermined moment. More precisely a programmer can't control its execution; rather it is called by the Finalize method. There are some limitations of destructors as in the following;. The following implements a destructor and dispose method. First of all we are initializing the fields via constructor, doing some calculations on that data and displaying it to the console.
But at line 9 we are implementing the destructor that is calling a Dispose method to release all the resources. At line 12 when the instance is created, fields are initialized but it is not necessary that at the same time the destructor is also called.
Its calling is dependent on garbage collection. If you want to see the destructor being called into action then put a breakpoint by F9 at line 10 and compile the application. The CLR indicates its execution at the end of the program by highlighting line 10 using the yellow color. Function overloading allows multiple implementations of the same function in a class. Overloaded methods share the same name but have a unique signature.
The number of parameters, types of parameters or both must be different. A function can't be overloaded on the basis of a different return type alone. At lines 3, 4 and 5 we are defining three methods with the same name but with different parameters.
In the Main , the moment you create an instance of the class and call the functions setName via obj at lines 7, 8 and 9 then intellisense will show three signatures automatically. Encapsulation is the mechanism that binds together the code and the data it manipulates, and keeps both safe from outside interference and misuse.
In OOP, code and data may be combined in such a way that a self-contained box is created. When code and data are linked together in this way, an object is created and encapsulation exists. Within an object, code, data or both may be private or public to that object.
Private code is known to and accessible only by another part of the object, that is private code or data may not be accessible by a piece of the program that exists outside the object. When the code and data is public, other portions of your program may access it even though it is defined within an object. Inheritance is the process by which one object can acquire the properties of another object. Inheritance is a "is a kind of" relationship and it supports the concept of classification in which an object needs only define those qualities that make it unique within the class.
Inheritance involves a base class and a derived class. The derived class inherits from the base class and also can override inherited members as well as add new members to extend the base class.
A base type represents the generalization, whereas a derived type represents a specification of an instance. Such as Employees that can have diverse types, such as hourly, salaried and temporary so in that case Employees is the general base class and hourly, salaried and temporary employee are specialized derived classes. Classes can inherit from a single class and one or more interfaces. When inheriting from a class, the derived class inherits the members including the code of the base class.
The important point to remember is that Constructors and Destructors are not inherited from the base class. For example we are defining two classes, Father and Child. You notice at line 7, we are implementing inheritance by using a colon : ; at this moment all the properties belonging to the Father Class is accessible to the Child class automatically.
At line 11 , the Intellisense only shows the Father class functions but at line 15 to 16 the Child class object is able to access both class methods as in the following. We can create a class in the VB. Net language or another. NET supported language and can inherit them in a C. Net class and vice versa. Accessibility sets the visibility of the member to outside assemblies or derived types.
The following table describes member accessibility;. Constructors in a base class are not inherited in a derived class. A derived class has a base portion and derived portion. The base portion initializes the base portion, and the constructor of the derived class initializes the derived portion. So the base keyword refers to the base class constructor, while parameterlist2 determines which overloaded base class constructor is called. In the following example, the Child class's constructor calls the single-argument constructor of the base Father class;.
At line 4, we are defining a base Father Class constructor and in the derived class Child, at line 8 we are initializing it explicitly via base keyword. If we pass any parameter in the base class constructor then we have to provide them in the base block of the child class constructor.
In the preceding tutorial, introduction to classes you saw both abstraction and encapsulation. The BankAccount class provided an abstraction for the concept of a bank account. You could modify its implementation without affecting any of the code that used the BankAccount class. Both the BankAccount and Transaction classes provide encapsulation of the components needed to describe those concepts in code.
In this tutorial, you'll extend that application to make use of inheritance and polymorphism to add new features. You'll also add features to the BankAccount class, taking advantage of the abstraction and encapsulation techniques you learned in the preceding tutorial. After building this program, you get requests to add features to it. It works great in the situation where there is only one bank account type. Over time, needs change, and related account types are requested:. All of these different accounts are similar to BankAccount class defined in the earlier tutorial.
You could copy that code, rename the classes, and make modifications. That technique would work in the short term, but it would be more work over time. Any changes would be copied across all the affected classes. Instead, you can create new bank account types that inherit methods and data from the BankAccount class created in the preceding tutorial. These new classes can extend the BankAccount class with the specific behavior needed for each type:.
Each of these classes inherits the shared behavior from their shared base class , the BankAccount class. Write the implementations for new and different functionality in each of the derived classes. These derived classes already have all the behavior defined in the BankAccount class. It's a good practice to create each new class in a different source file.
In Visual Studio , you can right-click on the project, and select add class to add a new class in a new file. In either tool, name the file to match the class: InterestEarningAccount. When you create the classes as shown in the preceding sample, you'll find that none of your derived classes compile. A constructor is responsible for initializing an object. A derived class constructor must initialize the derived class, and provide instructions on how to initialize the base class object included in the derived class.
The proper initialization normally happens without any extra code. The BankAccount class declares one public constructor with the following signature:. The compiler doesn't generate a default constructor when you define a constructor yourself. That means each derived class must explicitly call this constructor.
You declare a constructor that can pass arguments to the base class constructor. The following code shows the constructor for the InterestEarningAccount :. The parameters to this new constructor match the parameter type and names of the base class constructor. You use the : base syntax to indicate a call to a base class constructor.
Some classes define multiple constructors, and this syntax enables you to pick which base class constructor you call. Once you've updated the constructors, you can develop the code for each of the derived classes. The requirements for the new classes can be stated as follows:. You can see that all three of these account types have an action that takes places at the end of each month.
However, each account type does different tasks. You use polymorphism to implement this code. Create a single virtual method in the BankAccount class:. The preceding code shows how you use the virtual keyword to declare a method in the base class that a derived class may provide a different implementation for. A virtual method is a method where any derived class may choose to reimplement.
The derived classes use the override keyword to define the new implementation. Typically you refer to this as "overriding the base class implementation". The virtual keyword specifies that derived classes may override the behavior. You can also declare abstract methods where derived classes must override the behavior.
The base class does not provide an implementation for an abstract method. Next, you need to define the implementation for two of the new classes you've created. Start with the InterestEarningAccount :. Add the following code to the LineOfCreditAccount. The code negates the balance to compute a positive interest charge that is withdrawn from the account:.
The GiftCardAccount class needs two changes to implement its month-end functionality. First, modify the constructor to include an optional amount to add each month:. The constructor provides a default value for the monthlyDeposit value so callers can omit a 0 for no monthly deposit.
Next, override the PerformMonthEndTransactions method to add the monthly deposit, if it was set to a non-zero value in the constructor:. The override applies the monthly deposit set in the constructor.
Verify the results. Now, add a similar set of test code for the LineOfCreditAccount :. When you add the preceding code and run the program, you'll see something like the following error:. The actual output includes the full path to the folder with the project. The folder names were omitted for brevity.
0コメント