Example code about inheritance and polymorphism
本人学Asp.Net不久,用的是C#写代码,在学习C#中发现很多初学者对继承和多态性不是特别的了解,因此作了这个例子,希望对您有所帮助,例子很简单
页面文件TestProfileClass2.aspx
<%@ Page Language="C#" ContentType="text/html" ResponseEncoding="gb2312" Src="profile2.cs" %> <%@ Import Namespace="shai" %> <html> <head> <style> p{font:Arial, Helvetica, sans-serif; background-color :#cccccc; border-color :black; border-width :1; border-style :solid; padding:10,10,10,10; } </style> <script language="c#" runat="server"> public void Page_Load(Object sender,EventArgs e) { Profile profile = new Profile(); message.InnerHtml += "<u>Profile Class</u><br>"; message.InnerHtml += "Firstname:"+profile.getFirstname()+"<br>"; message.InnerHtml += "Lastname:"+profile.getLastname()+"<br>"; message.InnerHtml += "Phone:"+profile.getPhonenumber()+"<br><br>"; profile.save(); ExtendedProfile extendedprofile = new ExtendedProfile(); message.InnerHtml += "<u>ExtendedProfile Class</u></br>"; message.InnerHtml += "Firstname:"+profile.getFirstname()+"<br>"; message.InnerHtml += "Lastname:"+profile.getLastname()+"<br>"; message.InnerHtml += "Phone:"+extendedprofile.getPhonenumber()+"<br>"; message.InnerHtml += "Address1:"+extendedprofile.getAddress1()+"<br>"; message.InnerHtml += "Address2:"+extendedprofile.getAddress2()+"<br>"; message.InnerHtml += "City:"+extendedprofile.getCity()+"<br>"; message.InnerHtml += "State:"+extendedprofile.getState()+"<br>"; message.InnerHtml += "Postal:"+extendedprofile.getPostal()+"<br>"; message.InnerHtml += "Description:"+extendedprofile.getDescription()+"<br>"; extendedprofile.save(); } </script> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <title></title> </head> <body style="font:Arial, Helvetica, sans-serif "> <b><h3>简单的继承/多态例子</h3></b><br><br> object output:<br> <br> <p id="message" runat="server" /> </body> </html> 类定义文件profile2.cs using System; using System.IO; using System.Xml; namespace shai //名称空间shai { interface ISaveData //定义一个接口ISaveData,他作为Profile的基类被继承,由于其有多态性的特点,可以被 { //不同类调用其中的方法,并修改 void save(); } public class Profile:ISaveData //定义类Profile { protected string _firstname; //里面包含三个属性,分别为_firstname、_lastname、phonenumber protected string _lastname; protected string _phonenumber; public Profile() //为属性定义其中的初始值 { _firstname = "Saidy"; _lastname = "Chen"; _phonenumber = "(010)88716990"; } public string getPhonenumber() //Profile类中的方法getPhonenumber() { return _phonenumber; } public virtual void setPhonenumber(string phonenumber) { _phonenumber = phonenumber; } public string getFirstname() //Profile类中的方法getFirstname() { return _firstname; } public void setFirstname(string firstname) { _firstname = firstname; } public string getLastname() //Profile类中的方法getLastname() { return _lastname; } public void setLastname(string lastname) { _lastname = lastname; } public virtual void save() //调用ISaveData接口的save()方法 { //保存数据为Text格式 FileStream fs = new FileStream("D:\\myweb2\\profile2.txt",FileMode.Create,FileAccess.Write); StreamWriter sw = new StreamWriter(fs); sw.WriteLine("Firstname:"+_firstname.ToString()); sw.WriteLine("Lastname:"+_lastname.ToString()); sw.WriteLine("Phone:"+_phonenumber.ToString()); sw.Flush(); sw.Close(); fs.Close(); } } public class ExtendedProfile:Profile 建立Profile子类ExtendedProfile,他可以继承Profile中的方法 { protected string _address1; //子类ExtendedProfile的属性 protected string _address2; protected string _city; protected string _state; protected string _postal; protected string _description; public ExtendedProfile() //子类ExtendedProfile中属性的初始值 { _address1 = "清华大学"; _address2 = "清华大学物理实验室"; _city = "北京"; _state = "北京"; _postal = "100024"; _description = "教授"; } public override void setPhonenumber(string phonenumber) //继承类Profile中的setPhonenumber()方法 { //setPhonenumber()方法的重载 _phonenumber = phonenumber; } public string getAddress1() //子类ExtendedProfile中的方法getAddress1(),以下类推 { return _address1; } public string getAddress2() { return _address2; } public void setAddress(string address1,string address2) { _address1 = address1; _address2 = address2; } public string getCity() { return _city; } public void setCity(string city) { _city = city; } public string getState() { return _state; } public void setState(string state) { _state = state; } public string getPostal() { return _postal; } public void setPostal(string postal) { _postal = postal; } public string getDescription() { return _description; } public void setDescription(string description) { _description = description; } public override void save() //调用接口ISaveData()中的方法save(),save()方法的重载,由于多态性 { //子类ExtendedProfile可以自定义并修改save()方法 string _document = "d:\\myweb2\\saidy.xml"; XmlTextWriter writer = null; //保存为一个Xml文件 try { writer = new XmlTextWriter(_document,null); writer.Formatting = Formatting.Indented; writer.WriteStartDocument(false); writer.WriteDocType("Profile",null,null,null); //表示<!DOCTYPE Profile> writer.WriteStartElement("Profile"); //生成根元素 writer.WriteElementString("firstname",_firstname); //生成子元素 <firstname>_firstname</firstname> writer.WriteElementString("lastname",_lastname); writer.WriteElementString("phonenumber",_phonenumber); writer.WriteElementString("address1",_address1); writer.WriteElementString("address2",_address2); writer.WriteElementString("city",_city); writer.WriteElementString("state",_state); writer.WriteElementString("postal",_postal); writer.WriteEndElement(); writer.Flush(); writer.Close(); } catch(Exception ee) { Console.WriteLine("Exception:{0}",ee.ToString()); } } } }
The above is the detailed content of Example code about inheritance and polymorphism. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In function inheritance, use "base class pointer" and "derived class pointer" to understand the inheritance mechanism: when the base class pointer points to the derived class object, upward transformation is performed and only the base class members are accessed. When a derived class pointer points to a base class object, a downward cast is performed (unsafe) and must be used with caution.

Inheritance error debugging tips: Ensure correct inheritance relationships. Use the debugger to step through the code and examine variable values. Make sure to use the virtual modifier correctly. Examine the inheritance diamond problem caused by hidden inheritance. Check for unimplemented pure virtual functions in abstract classes.

Detailed explanation of C++ function inheritance: Master the relationship between "is-a" and "has-a" What is function inheritance? Function inheritance is a technique in C++ that associates methods defined in a derived class with methods defined in a base class. It allows derived classes to access and override methods of the base class, thereby extending the functionality of the base class. "is-a" and "has-a" relationships In function inheritance, the "is-a" relationship means that the derived class is a subtype of the base class, that is, the derived class "inherits" the characteristics and behavior of the base class. The "has-a" relationship means that the derived class contains a reference or pointer to the base class object, that is, the derived class "owns" the base class object. SyntaxThe following is the syntax for how to implement function inheritance: classDerivedClass:pu

Inheritance and polymorphism affect the coupling of classes: Inheritance increases coupling because the derived class depends on the base class. Polymorphism reduces coupling because objects can respond to messages in a consistent manner through virtual functions and base class pointers. Best practices include using inheritance sparingly, defining public interfaces, avoiding adding data members to base classes, and decoupling classes through dependency injection. A practical example showing how to use polymorphism and dependency injection to reduce coupling in a bank account application.

What is object-oriented programming? Object-oriented programming (OOP) is a programming paradigm that abstracts real-world entities into classes and uses objects to represent these entities. Classes define the properties and behavior of objects, and objects instantiate classes. The main advantage of OOP is that it makes code easier to understand, maintain and reuse. Basic Concepts of OOP The main concepts of OOP include classes, objects, properties and methods. A class is the blueprint of an object, which defines its properties and behavior. An object is an instance of a class and has all the properties and behaviors of the class. Properties are characteristics of an object that can store data. Methods are functions of an object that can operate on the object's data. Advantages of OOP The main advantages of OOP include: Reusability: OOP can make the code more

Advantages and Disadvantages of C++ Polymorphism: Advantages: Code Reusability: Common code can handle different object types. Extensibility: Easily add new classes without modifying existing code. Flexibility and maintainability: separation of behavior and type improves code flexibility. Disadvantages: Runtime overhead: Virtual function dispatch leads to increased overhead. Code Complexity: Multiple inheritance hierarchies add complexity. Binary size: Virtual function usage increases binary file size. Practical case: In the animal class hierarchy, polymorphism enables different animal objects to make sounds through Animal pointers.

Destructors are crucial in C++ polymorphism, ensuring that derived class objects properly clean up memory when they are destroyed. Polymorphism allows objects of different types to respond to the same method call. The destructor is automatically called when an object is destroyed to release its memory. The derived class destructor calls the base class destructor to ensure that the base class memory is released.

Interface: An implementationless contract interface defines a set of method signatures in Java but does not provide any concrete implementation. It acts as a contract that forces classes that implement the interface to implement its specified methods. The methods in the interface are abstract methods and have no method body. Code example: publicinterfaceAnimal{voideat();voidsleep();} Abstract class: Partially implemented blueprint An abstract class is a parent class that provides a partial implementation that can be inherited by its subclasses. Unlike interfaces, abstract classes can contain concrete implementations and abstract methods. Abstract methods are declared with the abstract keyword and must be overridden by subclasses. Code example: publicabstractcla
