Inheritance Based on Murach (ch 14) and Deitel

Inheritance Based on Murach (ch 14) and Deitel

Inheritance Based on Murach (ch 14) and Deitel 2012 1 Objectives

Applied Use any of the features of inheritance that are presented in this chapter as you develop the classes for your applications. Knowledge Explain how inheritance is used within the .NET Framework classes and how you can use it in your own classes. Explain why you might want to override the ToString, Equals, and GetHashCode methods of the Object class as you develop the code for a new class. Describe the use of the protected and virtual access modifiers for the members of a class. Describe the use of polymorphism. Describe the use of the Type class. Describe the use of explicit casting when working with the objects of a base class and its derived classes. Distinguish between an abstract class and a sealed class.

2 How inheritance works 3 Inheritance Explanation When inheritance is used, a derived class inherits the properties, methods, and other members of a base class. Then, the objects that are created from the derived class can use these

inherited members. The derived class can also provide its own members that extend the base class. In addition, the derived class can override properties and methods of the base class by providing replacement denitions for them. Ex.: System.Windows.Forms.Form. the .NET Framework class that all Windows forms inherit. It has public properties and methods (ex. Text property and the Close method. Two groups of members are listed for this class. The rst group includes the properties and methods that the class inherits from its base class. The second group includes the members that have been added to the derived class. In this case, the derived class includes ve new properties (the text box and button controls) and one new method (GetNewProduct). Although this gure doesnt show it, a derived class can also replace an inherited property or method with its own version of the property or method. 4

Inheritance Review Inheritance lets you create a new class based on an existing class. Then, the new class inherits the properties, methods, and other members of the existing class. A class that inherits from an existing class is called a derived class, child class, or subclass. A Class that another class inherits is called a base class, parent

class, or super class. A derived class can extend the base class by adding new properties, methods, or other members to the base class. It can also replace a member from the base class with its own version of the member. Depending on how thats done, this is called hiding or overriding. Any new form inherits the .NET Framework class named System.WindowsForms.Form. 5 The inheritance hierarchy for form control classes 6 The fully qualied name of a class includes the name of the namespace that the class belongs to. For example, the fully qualied name for the

ComboBox control is System.Windows.Forms.ComboBox. 7 Methods of the System.Object class 1. ToString() 2. Equals(object) 3. Equals(object1, object2) 4. ReferenceEquals(object1, object2) 5. GetType() 6. GetHashCode() 7. Finalize() 8. MemberwiseClone() 8

The Top: Methods of the System.Object class A derived class can provide its own implementation of one or more of these methods -> these methods may work differently from class to class. For example, the default implementation of the ToString method returns the fully qualied name of the objects type. Because thats not very useful, its common to override the ToString method to provide a more useful string representation. For example, a Customer class might override the ToString method so it returns the customers name. The Equals and GetHashCode methods are often used to provide a way to compare objects using values rather than instance references.

A static ReferenceEquals method that provides the same function as the static Equals method. TheReferenceEquals method lets you test two objects for reference equality even if the class overrides the Equals method. 9 The Top: garbage collection, Finalize, MemberwiseClone Unlike C++ and other languages that require you to manage memory, C# uses a mechanism known as garbage collection to automatically manage memory. When the garbage collector determines that the system is running low on memory and that the system is idle, it frees the memory for

any objects that dont have anymore references to them. Before it does that, though, it calls the Finalize method for each of those objects, even though the default implementation of this method doesnt do anything. Although you can override the Finalize method to provide specic nalization code for an object, you rarely need to do that.T The last method shown in this gure is MemberwiseClone. You can use this method to create a simple copy of an object that doesnt expose other objects as properties or elds. 10 HashCode The hash code for an object is an integer that uniquely identies the object. Object instances that are considered equal should return the same hash code. A common way to implement the GetHashCode method is to return

ToString().GetHashCode(). This returns the hash code of the objects ToString() result. 11 Business classes for a Product Maintenance application Overrides 12 The code for a simplified version of the Product base class public class Product {

public string Code { get; set; } public string Description { get; set; } public decimal Price { get; set; } public virtual string GetDisplayText(string sep) => Code + sep + Description + sep + Price.ToString("c"); } If a derived class doesnt override the GetDisplayText method, that class will simply inherit the version implemented by this class. As a result, creating a Virtual member gives you the option of overriding the member in the derived class or allowing the derived class to defer to the version of the member dened by the base class. 13 Access Modifiers Keyword Description

public protected Available to all classes. Available only to the current class or to derived classes. Available only to classes in the current assembly. Available to the current class, derived classes in the current assembly, or derived classes in other assemblies. internal protected internal private

Available only to the containing class 14 One More Time Class public protected internal private Class A B C D

public protected internal private A B C D SubClass (outside package) SubClass public protected internal private

A B C D private D public protected internal private A B C D

Class ASSEMBLY (outside package) public protected internal private A B C D 15 One more time: Access Modifiers (again, MSDN C# Programming Guide) public

The type or member can be accessed by any other code in the same assembly or another assembly that references it. protected The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class. internal The type or member can be accessed by any code in the same assembly, but not from another assembly. protected internal The type or member can be accessed by any code in the assembly in which it is declared, OR from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type. Note that: protected internal means "protected OR internal" (any class in the same assembly, or any derived class - even if it is in a different assembly). private The type or member can be accessed only by code in the same class or struct. 16 private Methods/Fields are Private

17 Overriding Methods The derived class can either fully replace (override) the base class member function, or the derived class can partially replace (augment) the base class member function. The latter is accomplished by having the derived class member function call the base class member function, if desired. 18 Overriding Methods virtual tells the compiler that this method CAN be overridden by derived classes public virtual int MyMethod() {};

override in the subclass, tells the compiler that this method is OVERRIDING the same method in the base class public override int MyMethod() {}; base in the subclass, calls the base classs method base.MyMethod(); 19 20

The syntax for creating subclasses To declare a subclass public class SubclassName : BaseClassName To create a constructor that calls a base class constructor public ClassName(parameterlist): base(parameterlist) To call a base class method or property base.MethodName(parameterlist) base.PropertyName

To hide a non-virtual method or property public new type name To override a virtual method or property public override type name 21 The code for a Book class public class Book : Product { public string Author { get; set; }// A new Additional property public Book(string code, string description, string author, decimal price) : base(code, description, price) { this.Author = author;

// Initializes the Author field after } // the base class constructor is called. public override string GetDisplayText(string sep) => this.Code + sep + this.Description + "( " + this.Author + ")" + sep + this.Price.ToString("c"); } Expression-bodied way to override a method public override string GetDisplayText(string sep) => base.GetDisplayText(sep) + "( " + this.Author + ")"; 22 override vs new (rare)* public class Base {

public virtual void DoIt() {} } public class Derived : Base { public override void DoIt() {} } Base b = new Derived(); b.DoIt(); // Calls Derived.DoIt ======================================================================================= public class Base { public virtual void DoIt() {} } public class Derived : Base { public new void DoIt() {}

} Base b = new Derived(); Derived d = new Derived(); b.DoIt(); // Calls Base.DoIt d.DoIt(); // Calls Derived.DoIt 23 Ke ep it Overriding Methods cont.

change aug me nte d 24 Polymorphism Polymorphism is one of the most important features of object-oriented programming and inheritance.

Polymorphism lets you treat objects of different types as if they were the same type by referring to a base class thats common to both objects. Ex: Book and Software classes. Because both of these classes inherit the Product class, objects created from these classes can be treated as if they were Product objects. One benet of polymorphism is that you can write generic code thats designed to work with a base class. Then, you can use that code with instances of any class thats derived from the base class. 25 is a 26 Three versions of the GetDisplayText method A virtual GetDisplayText method in the Product base class

public virtual string GetDisplayText(string sep) => code + sep + price.ToString("c") + sep + description; An overridden GetDisplayText method in the Book class public override string GetDisplayText(string sep) => base.GetDisplayText(sep) + sep + author; An overridden GetDisplayText method in the Software class public override string GetDisplayText(string sep) => base.GetDisplayText(sep) + sep + version; 27

Code that uses the overridden methods Book b = new Book("CS15", "Murach's C# 2015", "Anne Boehm", 56.50m); Software s = new Software("NPTK", ".NET Programmer's Toolkit", "4.5", 179.99m); Product p; //Remember Book is a Product p = b; MessageBox.Show(p.GetDisplayText("\n")); // Calls Book.GetDisplayText p = s; //Remember Software is a Product MessageBox.Show(p.GetDisplayText("\n")); // Calls Software.GetDisplayText 28 Polymorphism again

Polymorphism. is a feature of inheritance that lets you treat objects of different subclasses that are derived from the same base class as if they had the type of the base class. If, for example, Book is a subclass of Product, you can treat a Book object as if it were a Product object. If you access a virtual member of a base class object and the member is overridden in the subclasses of that class, polymorphism determines the member thats executed based on the objects type. For example, if you call the GetDisplayText method of a Product object, the GetDisplayText method of the Book class isexecuted if the object is a Book object. Polymorphism is most useful when you have two or more derived classes that use the same base class. It allows you to write generic code that targets the

base class rather than having to write specic code for each object type. 29 The Product Maintenance form 30 Two versions of the New Product form 31 Two versions of the New Product form public class Product { private string code; private string description; private decimal price; public Product()

{ } public Product(string Code, string Description, decimal Price) { this.Code = Code; this.Description = Description; this.Price = Price; } 32 Two versions of the New Product form cont. public string Code { get { return code; }

set { code = value; } } public string Description { get { return description; } set { description = value; } } 33

Two versions of the New Product form cont. public decimal Price { get { return price; } set { price = value; } } public virtual string GetDisplayText(string sep) => Code + sep + Price.ToString("c") + sep + Description; } 34 The code for the Book class

public class Book : Product { private string author; public Book() { } public Book(string code, string description, string author, decimal price) : base(code, description, price) { this.Author = author; } public string Author { get { return author; } set

{ author = value; } } public override string GetDisplayText(string sep) => base.GetDisplayText(sep) + " (" + Author + ")"; } 35 The code for the Software class public class Software : Product { private string version; public Software() { } public Software(string code, string description, string version,

decimal price) : base(code, description, price) { this.Version = version; } public string Version { get { return version; } set { version = value; } } public override string GetDisplayText(string sep) => base.GetDisplayText(sep) + ", Version " + Version; }

36 The code for the ProductList class public class ProductList : List { // Modify the behavior of the Add method of the List<> class public new void Add(Product p) => base.Insert(0, p); // Provide two additional methods public void Fill() { List products = ProductDB.GetProducts(); //get them foreach (Product product in products) //add base.Add(product); } public void Save() => ProductDB.SaveProducts(this); } This version of the ProductList class inherits the List<> class of

the .NET Framework. As a result, it doesnt need to dene a List<> instance variable because the class is itself a type of List<> class. 37 The code for the Product Maintenance form public partial class frmProductMain : Form { public frmProductMain() { InitializeComponent(); } private ProductList products = new ProductList(); private void frmProductMain_Load(object sender, EventArgs e) { products.Fill(); FillProductListBox(); }

private void FillProductListBox() { lstProducts.Items.Clear(); foreach (Product p in products) lstProducts.Items.Add(p.GetDisplayText("\t")); } 38 The code for the Product Maintenance form cont. private void btnAdd_Click(object sender, EventArgs e) { frmNewProduct newForm = new frmNewProduct(); Product product = newForm.GetNewProduct(); if (product != null) { products.Add(product); products.Save(); FillProductListBox(); }

} 39 The code for the Product Maintenance form cont. private void btnDelete_Click(object sender, EventArgs e) { int i = lstProducts.SelectedIndex; if (i != -1) { Product product = products[i]; string message = "Are you sure you want to delete " + product.Description + "?"; DialogResult button = MessageBox.Show(message, "Confirm Delete", MessageBoxButtons.YesNo); if (button == DialogResult.Yes) { products.Remove(product);

products.Save(); FillProductListBox(); } } private void btnExit_Click(object sender, EventArgs e) { this.Close(); } } 40 The code for the New Product form public partial class frmNewProduct : Form { public frmNewProduct() { InitializeComponent(); } private Product product = null;

public Product GetNewProduct() { this.ShowDialog(); return product; } private void rbBook_CheckedChanged(object sender, EventArgs e) { if (rbBook.Checked) { lblAuthorOrVersion.Text = "Author: "; txtAuthorOrVersion.Tag = "Author"; } else { lblAuthorOrVersion.Text = "Version: "; txtAuthorOrVersion.Tag = "Version"; } txtCode.Focus(); }

41 The code for the New Product form (cont) private void btnSave_Click(object sender, EventArgs e) { if (IsValidData()) { if (rbBook.Checked) product = new Book(txtCode.Text, txtDescription.Text, txtAuthorOrVersion.Text, Convert.ToDecimal(txtPrice.Text)); else product = new Software(txtCode.Text, txtDescription.Text, txtAuthorOrVersion.Text, Convert.ToDecimal(txtPrice.Text)); this.Close(); } } private bool IsValidData() {

return Validator.IsPresent(txtCode) && Validator.IsPresent(txtDescription) && Validator.IsPresent(txtAuthorOrVersion) && Validator.IsPresent(txtPrice) && Validator.IsDecimal(txtPrice); } 42 The code for the New Product form (cont.) private void btnCancel_Click(object sender, EventArgs e) { this.Close(); } 43 Code that uses the Type class to get information about an object Product p;

p = new Book("CS15", "Murach's C# 2015", "Anne Boehm", 56.50m); Type t = p.GetType(); Console.WriteLine("Name: " + t.Name); Console.WriteLine("Namespace: " + t.Namespace); Console.WriteLine("FullName: " + t.FullName); Console.WriteLine("BaseType: " + t.BaseType.Name); The result thats displayed on the console Name: Book Namespace: ProductMaintenance FullName: ProductMaintenance.Book BaseType: Product 44 How to test an objects type

if (p.GetType() == typeof(Book)) Another way to test an objects type if (p.GetType().Name == nameof(Book)) Two methods that display product information public void DisplayProduct(Product p) => MessageBox.Show(p.GetDisplayText()); public void DisplayBook(Book b) => MessageBox.Show(b.GetDisplayText()); 45 Using and Not Using Cast Code that doesnt require casting Book b = new Book("CS15", "Murach's C# 2015",

"Anne Boehm", 56.50m); DisplayProduct(b); // Casting is not required because //Book // is a subclass of Product. Code that requires casting Product p = new Book("CS15", "Murach's C# 2015", "Anne Boehm", 56.50m); DisplayBook((Book)p); // Casting is required because // DisplayBook accepts a Book // object 46 Code that throws a casting exception Product p = new Software("NPTK", ".NET Programmer's

Toolkit","4.5", 179.99m); DisplayBook((Book)p); // Will throw a casting exception // because p is a Software object, // not a Book object. Code that uses the as operator Product p = new Book("CS15", "Murach's C# 2015", "Anne Boehm", 56.50m); DisplaySoftware(p as Software); // Passes null because p // isn't a Software object 47 The Type class Property

Description Name Returns a string that contains the name of a type. Returns a string that contains the fully qualified name of a type, which includes the namespace name and the type name. FullName BaseType Namespace Method GetType()

Returns a Type object that represents the class that a type inherits. Returns a string that contains the name of the namespace that contains a type. Description Returns a Type object that represents the type of an object. 48 GetType Every object has a GetType method that returns a Type object that corresponds to the objects type.

You can use the properties of the Type class to obtain information about the type of any object, such as the types name and the name of its base class. The properties and methods shown on the previous slide are only some of the more than 90 properties and methods of the Type class. The easiest way to test an objects type is to compare the Type object thats returned by the GetType method of the object with the Type object thats returned by the typeof operator of a type.

Another way to test an objects type is to compare the name of an objects type with the name thats returned by the name of operator of a type. 49 Abstract Classes abstract class 50 Abstract Classes cont. 51 Abstract Classes cont.

An abstract class is a class that can be inherited by other classes but that you cant use to create an object. To declare an abstract class, code the abstract keyword in the class declaration. An abstract class can contain properties, methods, and other members just like other base classes. In addition, an abstract class can contain abstract methods and properties. To create an abstract method, you code the abstract keyword in the method declaration and you omit the method body. To create an abstract property, you code the abstract keyword in the

property declaration. Then, you code a get accessor, a set accessor, or both get and set accessors with no bodies. Abstract methods and properties are implicitly Virtual, and you cant code the Virtual keyword on an abstract method or property. When a subclass inherits an abstract class, all abstract methods and properties in the abstract class must be overridden in the subclass. The exception is if the subclass is also an abstract class. An abstract class doesnt have to contain abstract methods or properties. However, any class that contains an abstract method or property must be declared as abstract. 52 An abstract Product class public abstract class Product { public string Code { get; set; } public string Description { get; set; } public decimal Price { get; set; }

public abstract string GetDisplayText(string sep); // No method body is coded. } An abstract read-only property public abstract bool IsValid { get; // No body is coded for the get accessor. } 53 A class that inherits the abstract Product class public class Book : Product { public string Author { get; set; } public override string GetDisplayText(string sep) => this.Code + sep + this.Description +

"( " + this.Author + ")" + sep + this.Price.ToString("c"); } 54 Sealed Classes and Methods 55 The class declaration for a sealed Book class public sealed class Book : Product How sealed methods work A base class named A that declares a virtual method public class A {

public virtual void ShowMessage() => MessageBox.Show("Hello from class A"); } A class named B that inherits class A and overrides and seals its method public class B : A { public sealed override void ShowMessage() => MessageBox.Show("Hello from class B"); } 56 How sealed methods work A class named C that inherits class B and tries to override its sealed method public class C : B

{ public override void ShowMessage() => // MessageBox.Show("Hello from class C"); } Not allowed 57 Interfaces 58 Interfaces Ex 59 Extra 14-1

Use inheritance with the Inventory Maintenance application Add two classes to the Inventory Maintenance application that inherit the InvItem class, and add code to the forms to provide for these new classes. 60 Exercise 14-1 Create a Customer Maintenance application that uses inheritance Create classes for two types of customers that are derived from the Customer base class. Then, add the code that works with these classes. 61

Project 3-4 Create a memory calculator Create a form that lets the user perform the functions of a memory calculator. 62

Recently Viewed Presentations

  • Chapter 1

    Chapter 1

    Development Part 2: "Paths to Development" FIGURE 9-1 FIGURE 9-29 * Barriers to Development Structure and geography of the world economy (Wallerstein's World Systems Theory) Social conditions Lack of female empowerment Demographic trap (stress this is circular!!!!) high CBR, IMR,...
  • Aim: Were the falls of the Aztec and Incan Empires inevitable?

    Aim: Were the falls of the Aztec and Incan Empires inevitable?

    Bullet holes found in Incan skulls at the time of the Incan conquest. IV The Spanish Colonies. A) Spain divided their American colonies into 5 provinces, each ruled by a viceroy (governor). B) Jesuits (Catholic missionaries) forced the natives to...
  • Presenter - Civil Air Patrol National Headquarters

    Presenter - Civil Air Patrol National Headquarters

    Presenter. John "Moose" Desmarais. Director of Operations. National Headquarters. Rules of Engagement. Members in the field will be in listen only mode. We have several hundred members signed up, so having everyone with an open microphone is not supportable.
  • Greatest Common Factor - Teachers.Henrico Webserver

    Greatest Common Factor - Teachers.Henrico Webserver

    1. find the prime factorization of a number. 2. find the greatest common factor (GCF) for a set of monomials. SOL: A.2c Designed by Skip Tyler, Varina High School A prime number is a number that can only be divided...
  • Sound Reasoning 1 - Speech-Language Therapy

    Sound Reasoning 1 - Speech-Language Therapy

    Author: Caroline Bowen Created Date: 04/27/2010 21:13:10 Title: Sound Reasoning 1 Last modified by: CB
  • Chapter 8: A push for reform

    Chapter 8: A push for reform

    The Big Picture: The religious revival called the Second Great Awakening set off one of the great periods of social reform in American history. Inspired to do good works, the reformers changed the face of America. Chapter 8: A push...
  • Instructions for the WG Chair The IEEE-SA strongly

    Instructions for the WG Chair The IEEE-SA strongly

    The IEEE-SA strongly recommends that at each WG meeting the chair or a designee: Show slides #1 through #4 of this presentation Advise the WG attendees that: IEEE's patent policy is described in Clause 6 of the IEEE-SA Standards Board...
  • The Essential Guide to User Interface Design Second Edition

    The Essential Guide to User Interface Design Second Edition

    arial lucida sans unicode times new roman wingdings default design part 2 the user interface design process part 2 obstacles and pitfalls in the development path part 2 obstacles and pitfalls in the development path part 2 designing for people:...