C # object-oriented features: inheritance, encapsulation, and Polymorphism

Source: Internet
Author: User
The following describes three object-oriented features: inheritance, encapsulation, and polymorphism.
C # is a modern object-oriented language.
Inheritance: inheritance is an object-oriented word. description, which can be shared by a Class (derived class) and the features and behaviors of other classes (base classes ).

The relation between the Birth class and the base class is "is.
Base classes (base class): a base class can be instantiated by itself, or inherited. A derived class inherits members of the base class and is marked as protected or larger.

permission. syntax: Class (derive class name) :( base class name)
example:
// base class
public class contact
{< br> // default private field
string name;
string email;
string address;
// constructor
public contact ()
{< br> // statements...
}< br> // attribute
Public string name
{< br> Get
{< br> return name;
}< br> set
{< br> name = value;
}< BR >}

Public String email
{
Get
{
Return email;
}
Set
{
Email = value;
}
}

Public String address
{
Get
{
Return address;
}
Set
{
Address = value;
}
}
}
// Derived class
Public Class Customer: Contact
{
// Your own private field
String gender;
Decimal income;

Public customer ()
{
// Statements...
}
}
In the above example, the customer is

The Child class of contact not only inherits the members of the parent class, name, email, address; but also has its own members, gender, income.

Abstract classes (abstract class): An abstract class is a special base class. Apart from common class members, they also have abstract class members. abstract class members,

Is a method and attribute that cannot be instantiated. All classes derived directly from abstract classes must implement Abstract methods and attributes. abstract classes cannot be instantiated.
Example:
// Abstract class
Abstract Public class contact
{
Protected string name;

Public contact ()
{
// Statements...
}

// Abstract Method
Public abstract void generatereport ();
// Abstract attributes
Abstract Public string name
{
Get;
Set;
}}

Public Class Customer: Contact
{
String gender;
Decimal income;
Int numberofvisits;

Public customer ()
{
// Statements
}

Public override void generatereport ()
{
// Unique report
}

Public override string name
{
Get
{
Numberofvisits ++;
Return name;
}
Set
{
Name = value;
Numberofvisits = 0;
}
}
}

Public class siteowner: Contact
{
Int sitehits;
String mysite;

Public siteowner ()
{
// Statements...
}

Public override void generatereport ()
{
// Unique report
}

Public override string name
{
Get
{
Sitehits ++;
Return name;
}
Set
{
Name = value;
Sitehits = 0;
}
}
}
The preceding example defines three classes. An abstract class and two Derived classes. implements the methods and attributes of the parent class. The "Override" modifier implements the abstraction.

Class method.
Calling base class members (call base class members)
A derived class can call a base class member. If the modifier of a member is "protected" or has a higher permission, it seems to call its own

The members are the same.
Example:
Abstract Public class contact
{
Private string address;
Private string city;
Private string state;
Private string zip;

Public String fulladdress ()
{
String fulladdress =
Address + ''\ n' +
City + '','' + state + ''' + Zip;

Return fulladdress;
}
}

Public Class Customer: Contact
{
Public String generatereport ()
{
String fulladdress = fulladdress ();
// Do some other stuff...
Return fulladdress;
}
}
In the above example, the derived class calls the method of the base class: fulladdress ();
The constructor of the base class, which can be called by the derived class, using base ().
Example:
Abstract Public class contact
{
Private string address;

Public contact (string address)
{
This. Address = address;
}
}

Public Class Customer: Contact
{
Public customer (string address): Base (address)
{
}
}
In this example, the derived class does not have an address Member. You can call the constructor of the base class.
Hiding base class members (hiding base class members)
A derived class can have members with the same name as the base class. In this case, the base class members are hidden.
Example:
Abstract Public class contact
{
Private string address;
Private string city;
Private string state;
Private string zip;

Public String fulladdress ()
{
String fulladdress =
Address + ''\ n' +
City + '','' + state + ''' + Zip;

Return fulladdress;
}
}

Public class siteowner: Contact
{
Public String fulladdress ()
{
String fulladdress;

// Create an address...
Return fulladdress;
}
}
In this example, the derived class has the same member as the base class, fulladdress (). When called, the base class method will be hidden.

Although the member of the base class is hidden, you can still access the member of the base class and call the reference of the base class through the base keyword.
Example:
Abstract Public class contact
{
Private string address;
Private string city;
Private string state;
Private string zip;

Public String fulladdress ()
{
String fulladdress =
Address + ''\ n' +
City + '','' + state + ''' + Zip;

Return fulladdress;
}
}

Public class siteowner: Contact
{
Public String fulladdress ()
{
String fulladdress = base. fulladdress ();

// Do some other stuff...
Return fulladdress;
}
}
In this example, the derived class calls the base class member and uses the base class to reference it.
Visioning (Version)
Example:
Using system;
Public class website
{
Public String sitename;
Public String URL;
Public String description;

Public website ()
{
}

Public website (string strsitename, string strurl, string strdescription)
{
Sitename = strsitename;
Url = strurl;
Description = strdescription;
}

Public override string tostring ()
{
Return sitename + "," +
URL + "," +
Description;
}
}

Public class contact
{
Public String address;
Public String city;
Public String state;
Public String zip;

Public String fulladdress ()
{
String fulladdress =
Address + ''\ n' +
City + '','' + state + ''' + Zip;

Return fulladdress;
}
}

Public class siteowner: Contact
{
Int sitehits;
String name;
Website mysite;

Public siteowner ()
{
Mysite = new website ();
Sitehits = 0;
}

Public siteowner (string aname, website asite)
{
Mysite = new website (asite. sitename,
Asite. url,
Asite. Description );

Name = aname;
}

New Public String fulladdress ()
{
String fulladdress = mysite. tostring ();

Return fulladdress;
}

Public string name
{
Get
{
Sitehits ++;
Return name;
}
Set
{
Name = value;
Sitehits = 0;
}
}
}

Public class test
{
Public static void main ()
{
Website mysite = new website ("Le financier ",
"Http://www.LeFinancier.com ",
"Fancy financial site ");

Siteowner anowner = new siteowner ("John Doe", mysite );
String address;

Anowner. Address = "123 Lane ";
Anowner. City = "Some town ";
Anowner. State = "hi ";
Anowner.zip = "45678 ";

Address = anowner. fulladdress (); // different results
Console. writeline ("Address: \ n {0} \ n", address );

}
}
In this example, the derived class uses the new modifier, indicating that the base class has members with the same name.
Sealed classed (Seal class)
A sealed class is a class that cannot be inherited. To avoid inheritance from a class, a sealed class must be generated.
Example:
// Seal
Public sealed class customerstats
{
String gender;
Decimal income;
Int numberofvisits;

Public customerstats ()
{
}
}

Public class customerinfo: customerstats // Error
{
}

Public Class Customer
{
Customerstats mystats; // okay
}
In this example, the seal class cannot be inherited.

Encapsulation: encapsulation is an object-oriented concept that hides the interior of a class from the external world.
Encapsulation advantages:
1. Good encapsulation can reduce coupling.
2. The internal implementation of the class can be freely changed.
3. A class has a clearer interface.
Data Hiding: the most useful form of encapsulation is data hiding. Data of a class represents the state of an object.
Modifiers support encapsulation:
PRIVATE: only the class can be accessed.
Protected: classes and derived classes can be accessed.
Internal: only classes in the same project can be accessed.
Protected internal: A combination of protected and internal.
Public: full access.
Other encapsulating strategy: (Other encapsulation policies) attributes and indexers are used to encapsulate the details of a class and provide a public interface to the class users.
Encapsulation and inheritance:
Encapsulation means inclusion (aggregation). The relationship between classes is "has a". One class contains another class.
Inheritance. The relationship between classes is "is ".

Polymorphism: How to overload a virtual class. polymorphism is an important concept of object-oriented.
Implementing polymorphism (implementing polymorphism ):
Example:
Using system;
Public class website
{
Public String sitename;
Public String URL;
Public String description;

Public website ()
{
}

Public website (string strsitename, string strurl, string strdescription)
{
Sitename = strsitename;
Url = strurl;
Description = strdescription;
}

Public override string tostring ()
{
Return sitename + "," +
URL + "," +
Description;
}
}

Abstract Public class contact
{
Public Virtual string updatenoworkflow ()
{
Return "web site change notification ";
}
}

Public Class Customer: Contact
{
Public New String updatenoworkflow ()
{
Return @"
This is to let you know your
Favorite site, Financial Times,
Has been updated with new links ";
}
}

Public class siteowner: Contact
{
Website mysite;

Public siteowner (string aname, website asite)
{
Mysite = new website (asite. sitename,
Asite. url,
Asite. Description );
}

Public New String updatenoworkflow ()
{
Return @"
This is to let you know your site, "+" \ n "+
Mysite. sitename + @ ", has been added
A link to Financial Times .";
}
}

Public class test
{
Public static void main ()
{
Website lefin = new website ("Le financier ",
"Http://www.LeFinancier.com ",
"Fancy financial site ");

Contact [] contacts = new contact [2];

Contacts [0] = new siteowner ("Pierre doe", lefin );
Contacts [1] = new customer ();

Foreach (contact POC in contacts)
{
If (POC is siteowner)
{
Console. writeline ("message: {0} \ n ",
(Siteowner) POC). updatenoworkflow ());
}
Else
{
Console. writeline ("message: {0} \ n ",
(Customer) POC). updatenoworkflow ());
}
}
}
}
In this example, the contact class has a virtual method and two Derived classes are implemented respectively. The "new" keyword is used.
There can be more effective and elegant methods to achieve it, namely polymorphism.
Example:
Using system;
Abstract Public class contact
{
Public Virtual string updatenoworkflow ()
{
Return "web site change notification ";
}
}

Public Class Customer: Contact
{
Public override string updatenotify ()
{
Return @"
This is to let you know your
Favorite site, Financial Times,
Has been updated with new links ";
}
}

Public class siteowner: Contact
{
String sitename;

Public siteowner (string sname)
{
Sitename = sname;
}

Public override string updatenotify ()
{
Return @"
This is to let you know your site, "+" \ n "+
Sitename + @ ", has been added
A link to Financial Times .";
}
}
Public class test
{
Public static void main ()
{
Contact [] contacts = new contact [2];

Contacts [0] = new siteowner ("Le Er ");
Contacts [1] = new customer ();

Foreach (contact POC in contacts)
{
Console. writeline ("message: {0} \ n ",
POC. updatenoworkflow ());
}
}
}

In this example, the derived class uses "Override" to implement polymorphism.
A virtual method is a method of the base class that allows polymorphism. It is described with the "Override" modifier and can be overloaded by a derived class. Different Virtual Methods and abstract methods

Virtual methods are implemented, and abstract methods are not. abstract methods are implicitly described as virtual and must be overloaded. Virtual methods do not need to be overloaded.

Polymorphism. It must be a virtual method, and the method signature must be consistent, including the method name, parameter, and parameter type.
Example:
Abstract Public class contact
{
Public Virtual string updatenoworkflow ()
{
Return "web site change notification ";
}
}

Public Class Customer: Contact
{
Public override string Sendmail () {}// Error

Public override string updatenotify (INT number) {}// Error
}
In this example, Sendmail is not a virtual method, so it is incorrect. updatenoworkflow has different parameters, so it is also incorrect.

Both the new and override modifiers can implement the new method. However, the new method implements the new method of the derived class.
Example:
Using system;

Abstract Public class contact
{
Public Virtual string updatenoworkflow ()
{
Return "web site change notification ";
}
}

Public Class Customer: Contact
{
Public New String updatenoworkflow ()
{
Return @"
This is to let you know your
Favorite site, Financial Times,
Has been updated with new links ";
}
}

Public class siteowner: Contact
{
String sitename;

Public siteowner (string sname)
{
Sitename = sname;
}

Public override string updatenotify ()
{
Return @"
This is to let you know your site, "+" \ n "+
Sitename + @ ", has been added
A link to Financial Times .";
}
}

Public class test
{
Public static void main ()
{
Contact [] contacts = new contact [2];

Contacts [0] = new siteowner ("Le Er ");
Contacts [1] = new customer ();

Foreach (contact POC in contacts)
{
Console. writeline ("message: {0} \ n ",
POC. updatenoworkflow ());
}
}
}
The result is:
Message:
This is to let you know your site,
Le explorer, has been added
A link to Financial Times.

Message: web site Change Notification
In this example, the customer uses "new" to implement the new method. However, it still calls the method of the base class when running the program.

Most-derived implementations (Multi-derivative implementation)

Polymorphic properties (polymorphism attributes): C # Allow, polymorphism Implementation of attributes.
Example:
Using system;

Public class sitestats
{
Public int numberofvisits = 0;
}

Abstract Public class contact
{
Protected string name;

Public Virtual string name
{
Get
{
Return name;
}
Set
{
Name = value;
}
}
}

Public Class Customer: Contact
{
Sitestats mystats = new sitestats ();

Public override string name
{
Get
{
Mystats. numberofvisits ++;
Console. writeline ("number of visits: {0 }",
Mystats. numberofvisits );

Return name;
}
Set
{
Base. Name = value;
Mystats. numberofvisits = 0;
Console. writeline ("Name: {0}", name );
}
}
}

Public class test
{
Public static void main ()
{
Contact mycontact = new customer ();
Mycontact. Name = "George ";
}
}
In this example, the abstract class has an attribute name, and the derived class overload implements the attribute.

Polymorphic indexers: The polymorphism of the indexer.
Example:
Using system;
Using system. collections;
Public class sitelist
{
Protected sortedlist sites;

Public sitelist ()
{
Sites = new sortedlist ();
}

Public int nextindex
{
Get {
Return sites. count;
}
}

Public Virtual string this [int Index]
{
Get
{
Return (string) sites. getbyindex (INDEX );
}
Set
{
Sites [Index] = value;
}
}
}

Public class extends alsitelist: sitelist
{
Public override string this [int Index]
{
Get
{
Console. writeline ("externalsitelist indexer get ");
If (index> sites. Count)
Return (string) NULL;

Return base [Index];
}
Set
{
Console. writeline ("externalsitelist indexer set ");
Base [Index] = value;
}
}
}

Class SiteManager
{
Sitelist sites = new sitelist ();

Public static void main ()
{
SiteManager Mgr = new SiteManager ();

Mgr. sites = new catalog alsitelist ();

Mgr. sites [Mgr. sites. nextindex] = "great site! ";

Console. writeline ("site: {0 }",
Mgr. sites [0]. tostring ());
}
}
In this example, the base class indexer is "virtual", and the derived class reloads the indexer.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.