Presentation is loading. Please wait.

Presentation is loading. Please wait.

Based on Murach (ch 14) and Deitel 2012

Similar presentations


Presentation on theme: "Based on Murach (ch 14) and Deitel 2012"— Presentation transcript:

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

2 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.

3 How inheritance works

4 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 definitions 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 first 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 five new properties (the text box and button controls) and one new method (GetNewProduct). Although this figure doesn’t show it, a derived class can also replace an inherited property or method with its own version of the property or method.

5 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 that’s done, this is called hiding or overriding. Any new form inherits the .NET Framework class named System.WindowsForms.Form.

6 The inheritance hierarchy for form control classes

7 The fully qualified name of a class
includes the name of the namespace that the class belongs to. For example, the fully qualified name for the ComboBox control is System.Windows.Forms.ComboBox.

8 Methods of the System.Object class
ToString() Equals(object) Equals(object1, object2) ReferenceEquals(object1, object2) GetType() GetHashCode() Finalize() MemberwiseClone()

9 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 qualified name of the object’s type. Because that’s not very useful, it’s 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 customer’s 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.

10 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 don’t 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 doesn’t do anything. Although you can override the Finalize method to provide specific finalization code for an object, you rarely need to do that.T The last method shown in this figure is MemberwiseClone. You can use this method to create a simple copy of an object that doesn’t expose other objects as properties or fields.

11 HashCode The hash code for an object is an integer that uniquely identifies 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 object’s ToString() result.

12 Business classes for a Product Maintenance application
Overrides

13 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 doesn’t 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 defined by the base class.

14 Access Modifiers Keyword Description public Available to all classes.
protected Available only to the current class or to derived classes. internal Available only to classes in the current assembly. protected internal Available to the current class, derived classes in the current assembly, or derived classes in other assemblies. private Available only to the containing class

15 One More Time Class Class SubClass SubClass ASSEMBLY Class public A
protected B internal C private D Class public A protected B internal C private D SubClass (outside package) public A protected B internal C private D SubClass public A protected B internal C private D ASSEMBLY Class (outside package) public A protected B internal C private D

16 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.

17 private Methods/Fields are Private

18 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.

19 public override int MyMethod() {…};
Overriding Methods virtual – tells the compiler that this method CAN be overridden by derived classes override – in the subclass, tells the compiler that this method is OVERRIDING the same method in the base class base – in the subclass, calls the base class’s method public virtual int MyMethod() {…}; public override int MyMethod() {…}; base.MyMethod();

20

21 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

22 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 + ")";

23 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 new void DoIt() {} Derived d = new Derived(); b.DoIt(); // Calls Base.DoIt d.DoIt(); // Calls Derived.DoIt

24 Overriding Methods cont.
Keep it change augmented

25 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 that’s 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 benefit of polymorphism is that you can write generic code that’s designed to work with a base class. Then, you can use that code with instances of any class that’s derived from the base class.

26 “is a”

27 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 base.GetDisplayText(sep) + sep + version;

28 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", m); Product p; //Remember Book is a Product p = b; MessageBox.Show(p.GetDisplayText("\n")); // Calls Book.GetDisplayText p = s; //Remember Software is a Product // Calls Software.GetDisplayText

29 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 that’s executed based on the object’s 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 specific code for each object type.

30 The Product Maintenance form

31 Two versions of the New Product form

32 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;

33 Two versions of the New Product form cont.
public string Code { get return code; } set code = value; public string Description return description; description = value;

34 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;

35 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 + ")";

36 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;

37 The code for the ProductList class
public class ProductList : List<Product> { // 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<Product> 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 doesn’t need to define a List<> instance variable because the class is itself a type of List<> class.

38 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"));

39 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(); }

40 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();

41 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();

42 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, this.Close(); } private bool IsValidData() return Validator.IsPresent(txtCode) && Validator.IsPresent(txtDescription) && Validator.IsPresent(txtAuthorOrVersion) && Validator.IsPresent(txtPrice) && Validator.IsDecimal(txtPrice);

43 The code for the New Product form (cont.)
private void btnCancel_Click(object sender, EventArgs e) { this.Close(); }

44 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 that’s displayed on the console Name: Book Namespace: ProductMaintenance FullName: ProductMaintenance.Book BaseType: Product

45 How to test an object’s type
if (p.GetType() == typeof(Book)) Another way to test an object’s 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());

46 Using and Not Using Cast
Code that doesn’t 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", DisplayBook((Book)p); // Casting is required because // DisplayBook accepts a Book // object

47 Code that throws a casting exception
Product p = new Software("NPTK", ".NET Programmer's Toolkit","4.5", m); 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

48 The Type class Property Description Name
Returns a string that contains the name of a type. FullName Returns a string that contains the fully qualified name of a type, which includes the namespace name and the type name. BaseType Returns a Type object that represents the class that a type inherits. Namespace Returns a string that contains the name of the namespace that contains a type. Method GetType() Returns a Type object that represents the type of an object.

49 GetType Every object has a GetType method that returns a Type object that corresponds to the object’s type. You can use the properties of the Type class to obtain information about the type of any object, such as the type’s 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 object’s type is to compare the Type object that’s returned by the GetType method of the object with the Type object that’s returned by the typeof operator of a type. Another way to test an object’s type is to compare the name of an object’s type with the name that’s returned by the name of operator of a type.

50 Abstract Classes abstract class

51 Abstract Classes cont.

52 Abstract Classes cont. An abstract class is a class that can be inherited by other classes but that you can’t 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 can’t 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 doesn’t have to contain abstract methods or properties. However, any class that contains an abstract method or property must be declared as abstract.

53 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.

54 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"); }

55 Sealed Classes and Methods

56 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");

57 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() => // Not allowed MessageBox.Show("Hello from class C"); }

58 Interfaces

59 Interfaces Ex

60 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.

61 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.

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


Download ppt "Based on Murach (ch 14) and Deitel 2012"

Similar presentations


Ads by Google