SlideShare a Scribd company logo
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 1
Chapter 14
How to work with
inheritance
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 2
Objectives
Applied
1. Use any of the features of inheritance that are presented in this
chapter as you develop the classes for your applications.
Knowledge
1. Explain how inheritance is used within the .NET Framework
classes.
2. 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.
3. Describe the use of the protected and virtual access modifiers for
the members of a class.
4. Describe the use of polymorphism.
5. Describe the use of the Type class.
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 3
Objectives (continued)
6. Describe the use of explicit casting when working with the
objects of a base class and its derived classes.
7. Distinguish between an abstract class and a sealed class.
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 4
How inheritance works
Base class
System.Windows.Forms.Form
string Text
bool MinimizeBox
bool MaximizeBox
void Close()
void Show()
DialogResult ShowDialog()
ProductMaintenance.frmNewProduct
TextBox txtCode
TextBox txtDescription
TextBox txtPrice
Button btnSave
Button btnClose
Product GetNewProduct()
string Text
bool MinimizeBox
bool MaximizeBox
void Close()
void Show()
DialogResult ShowDialog()Derived
class
Inherited properties
and methods
Added properties
and methods
Public properties
and methods
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 5
The inheritance hierarchy for form control classes
Control
ButtonBase
Button
CheckBox
RadioButton
GroupBox
Label
ListControl
ComboBox
ListBox
TextBoxBase
TextBox
ScrollableControl
ContainerControl
Form
System.Windows.Forms namespace
Object
System namespace
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 6
Methods of the System.Object class
• ToString()
• Equals(object)
• Equals(object1, object2)
• ReferenceEquals(object1, object2)
• GetType()
• GetHashCode()
• Finalize()
• MemberwiseClone()
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 7
Business classes
for a Product Maintenance application
Product
string Code
string Description
decimal Price
string GetDisplayText(string)
Software
string Code
string Description
decimal Price
string GetDisplayText(string)
string Version
Book
string Code
string Description
decimal Price
string GetDisplayText(string)
string Author
System.Collections.Generic.List<Product>
Product this[index]
void Add(product)
void Remove(product)
ProductList
void Add(product)
void Fill()
void Save()
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 8
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)
{
return Code + sep + Description + sep
+ Price.ToString("c");
}
}
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 9
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 only to the current class, derived
classes, or classes in the current assembly.
private Available only to the containing class.
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 10
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(parameter-list) : base(parameter-list)
To call a base class method or property
base.MethodName(parameter-list)
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
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 11
The code for a Book class
public class Book : Product
{
public string Author { get; set; } // A new 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)
{
return this.Code + sep + this.Description
+ "( " + this.Author + ")" + sep
+ this.Price.ToString("c");
}
}
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 12
Another way to override a method
public override string GetDisplayText(string sep)
{
return base.GetDisplayText(sep) +
"( " + this.Author + ")";
}
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 13
Three versions of the GetDisplayText method
A virtual GetDisplayText method in the Product base
class
public virtual string GetDisplayText(string sep)
{
return code + sep + price.ToString("c") + sep
+ description;
}
An overridden GetDisplayText method in the Book class
public override string GetDisplayText(string sep)
{
return base.GetDisplayText(sep) + sep + author;
}
An overridden GetDisplayText method in the Software
class
public override string GetDisplayText(string sep)
{
return base.GetDisplayText(sep) + sep + version;
}
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 14
Code that uses the overridden methods
Book b = new Book("CS10", "Murach's C# 2010",
"Joel Murach", 54.50m);
Software s = new Software("NPTK",
".NET Programmer's Toolkit", "4.0", 179.99m);
Product p;
p = b;
MessageBox.Show(p.GetDisplayText("n"));
// Calls Book.GetDisplayText
p = s;
MessageBox.Show(p.GetDisplayText("n"));
// Calls Software.GetDisplayText
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 15
The Product Maintenance form
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 16
Two versions of the New Product form
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 17
The code for the Product class
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;
}
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 18
The code for the Product class (cont.)
public string Code
{
get
{
return code;
}
set
{
code = value;
}
}
public string Description
{
get
{
return description;
}
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 19
The code for the Product class (cont.)
set
{
description = value;
}
}
public decimal Price
{
get
{
return price;
}
set
{
price = value;
}
}
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 20
The code for the Product class (cont.)
public virtual string GetDisplayText(string sep)
{
return Code + sep + Price.ToString("c") + sep
+ Description;
}
}
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 21
The code for the Book class
public class Book : Product
{
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;
}
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 22
The code for the Book class (cont.)
set
{
author = value;
}
}
public override string GetDisplayText(string sep)
{
return base.GetDisplayText(sep) + " ("
+ Author + ")";
}
}
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 23
The code for the Software class
public class Software : Product
{
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;
}
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 24
The code for the Software class (cont.)
set
{
version = value;
}
}
public override string GetDisplayText(string sep)
{
return base.GetDisplayText(sep) + ", Version "
+ Version;
}
}
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 25
The code for the ProductList class
public class ProductList : List<Product>
{
// Modify the behavior of the Add method of the
// List<Product> class
public new void Add(Product p)
{
base.Insert(0, p);
}
// Provide two additional methods
public void Fill()
{
List<Product> products = ProductDB.GetProducts();
foreach (Product product in products)
base.Add(product);
}
public void Save()
{
ProductDB.SaveProducts(this);
}
}
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 26
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,
System.EventArgs e)
{
products.Fill();
FillProductListBox();
}
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 27
The code for the Product Maintenance form
(cont.)
private void FillProductListBox()
{
lstProducts.Items.Clear();
foreach (Product p in products)
lstProducts.Items.Add(p.GetDisplayText("t"));
}
private void btnAdd_Click(object sender,
System.EventArgs e)
{
frmNewProduct newForm = new frmNewProduct();
Product product = newForm.GetNewProduct();
if (product != null)
{
products.Add(product);
products.Save();
FillProductListBox();
}
}
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 28
The code for the Product Maintenance form
(cont.)
private void btnDelete_Click(object sender,
System.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();
}
}
}
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 29
The code for the Product Maintenance form
(cont.)
private void btnExit_Click(object sender,
System.EventArgs e)
{
this.Close();
}
}
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 30
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;
}
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 31
The code for the New Product form (cont.)
private void rbBook_CheckedChanged(object sender,
System.EventArgs e)
{
if (rbBook.Checked)
{
lblAuthorOrVersion.Text = "Author: ";
txtAuthorOrVersion.Tag = "Author";
}
else
{
lblAuthorOrVersion.Text = "Version: ";
txtAuthorOrVersion.Tag = "Version";
}
txtCode.Focus();
}
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 32
The code for the New Product form (cont.)
private void btnSave_Click(object sender,
System.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();
}
}
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 33
The code for the New Product form (cont.)
private bool IsValidData()
{
return Validator.IsPresent(txtCode) &&
Validator.IsPresent(txtDescription) &&
Validator.IsPresent(txtAuthorOrVersion) &&
Validator.IsPresent(txtPrice) &&
Validator.IsDecimal(txtPrice);
}
private void btnCancel_Click(object sender,
System.EventArgs e)
{
this.Close();
}
}
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 34
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 Description
GetType(fullname) A static method that returns a Type object for
the specified name.
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 35
Code that uses the Type class to get information
about an object
Product p;
p = new Book("CS10", "Murach's C# 2010",
"Joel Murach", 59.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
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 36
How to test an object’s type
if (p.GetType().Name == "Book")
Another way to test an object’s type
if (p.GetType() ==
Type.GetType("ProductMaintenance.Book"))
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 37
Two methods that display product information
public void DisplayProduct(Product p)
{
MessageBox.Show(p.GetDisplayText());
}
public void DisplayBook(Book b)
{
MessageBox.Show(b.GetDisplayText());
}
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 38
Code that doesn’t require casting
Book b = new Book("CS10", "Murach's C# 2010",
"Joel Murach", 54.50m);
DisplayProduct(b); // Casting is not required because
// Book is a subclass of Product.
Code that requires casting
Product p = new Book("CS10", "Murach's C# 2010",
"Joel Murach", 54.50m);
DisplayBook((Book)p); // Casting is required because
// DisplayBook accepts a Book
// object.
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 39
Code that throws a casting exception
Product p = new Software("NPTK",
".NET Programmer's Toolkit", "4.0", 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("CS10", "Murach's C# 2010",
"Joel Murach", 54.50m);
DisplaySoftware(p as Software);
// Passes null because p isn’t a Software object
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 40
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.
}
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 41
A class that inherits the abstract Product class
public class Book : Product
{
public string Author {get; set; }
public override string GetDisplayText(string sep)
{
return this.Code + sep + this.Description
+ "( " + this.Author + ")" + sep
+ this.Price.ToString("c");
}
}
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 42
The class declaration for a sealed Book class
public sealed class Book : Product
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 43
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");
}
}
Murach’s C#
2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 44
How sealed methods work (cont.)
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");
}
}

More Related Content

What's hot

What's hot (20)

C# Tutorial MSM_Murach chapter-20-slides
C# Tutorial MSM_Murach chapter-20-slidesC# Tutorial MSM_Murach chapter-20-slides
C# Tutorial MSM_Murach chapter-20-slides
 
C# Tutorial MSM_Murach chapter-12-slides
C# Tutorial MSM_Murach chapter-12-slidesC# Tutorial MSM_Murach chapter-12-slides
C# Tutorial MSM_Murach chapter-12-slides
 
C# Tutorial MSM_Murach chapter-22-slides
C# Tutorial MSM_Murach chapter-22-slidesC# Tutorial MSM_Murach chapter-22-slides
C# Tutorial MSM_Murach chapter-22-slides
 
C# Tutorial MSM_Murach chapter-05-slides
C# Tutorial MSM_Murach chapter-05-slidesC# Tutorial MSM_Murach chapter-05-slides
C# Tutorial MSM_Murach chapter-05-slides
 
C# Tutorial MSM_Murach chapter-01-slides
C# Tutorial MSM_Murach chapter-01-slidesC# Tutorial MSM_Murach chapter-01-slides
C# Tutorial MSM_Murach chapter-01-slides
 
C# Tutorial MSM_Murach chapter-10-slides
C# Tutorial MSM_Murach chapter-10-slidesC# Tutorial MSM_Murach chapter-10-slides
C# Tutorial MSM_Murach chapter-10-slides
 
C# Tutorial MSM_Murach chapter-09-slides
C# Tutorial MSM_Murach chapter-09-slidesC# Tutorial MSM_Murach chapter-09-slides
C# Tutorial MSM_Murach chapter-09-slides
 
C# Tutorial MSM_Murach chapter-23-slides
C# Tutorial MSM_Murach chapter-23-slidesC# Tutorial MSM_Murach chapter-23-slides
C# Tutorial MSM_Murach chapter-23-slides
 
C# Tutorial MSM_Murach chapter-03-slides
C# Tutorial MSM_Murach chapter-03-slidesC# Tutorial MSM_Murach chapter-03-slides
C# Tutorial MSM_Murach chapter-03-slides
 
C# Tutorial MSM_Murach chapter-02-slides
C# Tutorial MSM_Murach chapter-02-slidesC# Tutorial MSM_Murach chapter-02-slides
C# Tutorial MSM_Murach chapter-02-slides
 
C# Tutorial MSM_Murach chapter-19-slides
C# Tutorial MSM_Murach chapter-19-slidesC# Tutorial MSM_Murach chapter-19-slides
C# Tutorial MSM_Murach chapter-19-slides
 
C# Tutorial MSM_Murach chapter-21-slides
C# Tutorial MSM_Murach chapter-21-slidesC# Tutorial MSM_Murach chapter-21-slides
C# Tutorial MSM_Murach chapter-21-slides
 
C# Tutorial MSM_Murach chapter-17-slides
C# Tutorial MSM_Murach chapter-17-slidesC# Tutorial MSM_Murach chapter-17-slides
C# Tutorial MSM_Murach chapter-17-slides
 
C# Tutorial MSM_Murach chapter-06-slides
C# Tutorial MSM_Murach chapter-06-slidesC# Tutorial MSM_Murach chapter-06-slides
C# Tutorial MSM_Murach chapter-06-slides
 
C# Tutorial MSM_Murach chapter-08-slides
C# Tutorial MSM_Murach chapter-08-slidesC# Tutorial MSM_Murach chapter-08-slides
C# Tutorial MSM_Murach chapter-08-slides
 
C# Tutorial MSM_Murach chapter-04-slides
C# Tutorial MSM_Murach chapter-04-slidesC# Tutorial MSM_Murach chapter-04-slides
C# Tutorial MSM_Murach chapter-04-slides
 
Intake 38 9
Intake 38 9Intake 38 9
Intake 38 9
 
Intake 38 8
Intake 38 8Intake 38 8
Intake 38 8
 
Intake 37 9
Intake 37 9Intake 37 9
Intake 37 9
 
Chapter 2 — Program and Graphical User Interface Design
Chapter 2 — Program and Graphical User Interface DesignChapter 2 — Program and Graphical User Interface Design
Chapter 2 — Program and Graphical User Interface Design
 

Similar to C# Tutorial MSM_Murach chapter-14-slides

Java căn bản - Chapter4
Java căn bản - Chapter4Java căn bản - Chapter4
Java căn bản - Chapter4
Vince Vo
 
Refactoring - improving the smell of your code
Refactoring - improving the smell of your codeRefactoring - improving the smell of your code
Refactoring - improving the smell of your code
vmandrychenko
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
mwillmer
 
27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examples27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examples
Quang Suma
 
Tcs sample technical placement paper level i
Tcs sample technical placement paper level iTcs sample technical placement paper level i
Tcs sample technical placement paper level i
Pooja Reddy
 
Visual studio 2008
Visual studio 2008Visual studio 2008
Visual studio 2008
Luis Enrique
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
arjun431527
 

Similar to C# Tutorial MSM_Murach chapter-14-slides (20)

VR Workshop #2
VR Workshop #2VR Workshop #2
VR Workshop #2
 
C++ Interface Versioning
C++ Interface VersioningC++ Interface Versioning
C++ Interface Versioning
 
Presentation on design pattern software project lll
 Presentation on design pattern  software project lll  Presentation on design pattern  software project lll
Presentation on design pattern software project lll
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
What's New in Visual Studio 2008
What's New in Visual Studio 2008What's New in Visual Studio 2008
What's New in Visual Studio 2008
 
Foundations of programming
Foundations of programmingFoundations of programming
Foundations of programming
 
Factory method pattern (Virtual Constructor)
Factory method pattern (Virtual Constructor)Factory method pattern (Virtual Constructor)
Factory method pattern (Virtual Constructor)
 
Java căn bản - Chapter4
Java căn bản - Chapter4Java căn bản - Chapter4
Java căn bản - Chapter4
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
 
Refactoring - improving the smell of your code
Refactoring - improving the smell of your codeRefactoring - improving the smell of your code
Refactoring - improving the smell of your code
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
 
.Net december 2017 updates - Tamir Dresher
.Net december 2017 updates - Tamir Dresher.Net december 2017 updates - Tamir Dresher
.Net december 2017 updates - Tamir Dresher
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
22316-2019-Summer-model-answer-paper.pdf
22316-2019-Summer-model-answer-paper.pdf22316-2019-Summer-model-answer-paper.pdf
22316-2019-Summer-model-answer-paper.pdf
 
27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examples27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examples
 
Express 070 536
Express 070 536Express 070 536
Express 070 536
 
Tcs sample technical placement paper level i
Tcs sample technical placement paper level iTcs sample technical placement paper level i
Tcs sample technical placement paper level i
 
Visual studio 2008
Visual studio 2008Visual studio 2008
Visual studio 2008
 
1z0 804 exam-java se 7 programmer ii
1z0 804 exam-java se 7 programmer ii1z0 804 exam-java se 7 programmer ii
1z0 804 exam-java se 7 programmer ii
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
 

More from Sami Mut (6)

MSM_Time
MSM_TimeMSM_Time
MSM_Time
 
chapter 5 Java at rupp cambodia
chapter 5 Java at rupp cambodiachapter 5 Java at rupp cambodia
chapter 5 Java at rupp cambodia
 
chapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodiachapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodia
 
chapter 3 Java at rupp cambodia
chapter 3 Java at rupp cambodiachapter 3 Java at rupp cambodia
chapter 3 Java at rupp cambodia
 
chapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodiachapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodia
 
chapter 1 Java at rupp cambodia
chapter 1 Java at rupp cambodiachapter 1 Java at rupp cambodia
chapter 1 Java at rupp cambodia
 

Recently uploaded

Recently uploaded (20)

Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2
 
НАДІЯ ФЕДЮШКО БАЦ «Професійне зростання QA спеціаліста»
НАДІЯ ФЕДЮШКО БАЦ  «Професійне зростання QA спеціаліста»НАДІЯ ФЕДЮШКО БАЦ  «Професійне зростання QA спеціаліста»
НАДІЯ ФЕДЮШКО БАЦ «Професійне зростання QA спеціаліста»
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 

C# Tutorial MSM_Murach chapter-14-slides

  • 1. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 1 Chapter 14 How to work with inheritance
  • 2. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 2 Objectives Applied 1. Use any of the features of inheritance that are presented in this chapter as you develop the classes for your applications. Knowledge 1. Explain how inheritance is used within the .NET Framework classes. 2. 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. 3. Describe the use of the protected and virtual access modifiers for the members of a class. 4. Describe the use of polymorphism. 5. Describe the use of the Type class.
  • 3. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 3 Objectives (continued) 6. Describe the use of explicit casting when working with the objects of a base class and its derived classes. 7. Distinguish between an abstract class and a sealed class.
  • 4. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 4 How inheritance works Base class System.Windows.Forms.Form string Text bool MinimizeBox bool MaximizeBox void Close() void Show() DialogResult ShowDialog() ProductMaintenance.frmNewProduct TextBox txtCode TextBox txtDescription TextBox txtPrice Button btnSave Button btnClose Product GetNewProduct() string Text bool MinimizeBox bool MaximizeBox void Close() void Show() DialogResult ShowDialog()Derived class Inherited properties and methods Added properties and methods Public properties and methods
  • 5. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 5 The inheritance hierarchy for form control classes Control ButtonBase Button CheckBox RadioButton GroupBox Label ListControl ComboBox ListBox TextBoxBase TextBox ScrollableControl ContainerControl Form System.Windows.Forms namespace Object System namespace
  • 6. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 6 Methods of the System.Object class • ToString() • Equals(object) • Equals(object1, object2) • ReferenceEquals(object1, object2) • GetType() • GetHashCode() • Finalize() • MemberwiseClone()
  • 7. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 7 Business classes for a Product Maintenance application Product string Code string Description decimal Price string GetDisplayText(string) Software string Code string Description decimal Price string GetDisplayText(string) string Version Book string Code string Description decimal Price string GetDisplayText(string) string Author System.Collections.Generic.List<Product> Product this[index] void Add(product) void Remove(product) ProductList void Add(product) void Fill() void Save()
  • 8. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 8 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) { return Code + sep + Description + sep + Price.ToString("c"); } }
  • 9. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 9 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 only to the current class, derived classes, or classes in the current assembly. private Available only to the containing class.
  • 10. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 10 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(parameter-list) : base(parameter-list) To call a base class method or property base.MethodName(parameter-list) 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
  • 11. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 11 The code for a Book class public class Book : Product { public string Author { get; set; } // A new 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) { return this.Code + sep + this.Description + "( " + this.Author + ")" + sep + this.Price.ToString("c"); } }
  • 12. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 12 Another way to override a method public override string GetDisplayText(string sep) { return base.GetDisplayText(sep) + "( " + this.Author + ")"; }
  • 13. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 13 Three versions of the GetDisplayText method A virtual GetDisplayText method in the Product base class public virtual string GetDisplayText(string sep) { return code + sep + price.ToString("c") + sep + description; } An overridden GetDisplayText method in the Book class public override string GetDisplayText(string sep) { return base.GetDisplayText(sep) + sep + author; } An overridden GetDisplayText method in the Software class public override string GetDisplayText(string sep) { return base.GetDisplayText(sep) + sep + version; }
  • 14. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 14 Code that uses the overridden methods Book b = new Book("CS10", "Murach's C# 2010", "Joel Murach", 54.50m); Software s = new Software("NPTK", ".NET Programmer's Toolkit", "4.0", 179.99m); Product p; p = b; MessageBox.Show(p.GetDisplayText("n")); // Calls Book.GetDisplayText p = s; MessageBox.Show(p.GetDisplayText("n")); // Calls Software.GetDisplayText
  • 15. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 15 The Product Maintenance form
  • 16. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 16 Two versions of the New Product form
  • 17. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 17 The code for the Product class 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; }
  • 18. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 18 The code for the Product class (cont.) public string Code { get { return code; } set { code = value; } } public string Description { get { return description; }
  • 19. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 19 The code for the Product class (cont.) set { description = value; } } public decimal Price { get { return price; } set { price = value; } }
  • 20. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 20 The code for the Product class (cont.) public virtual string GetDisplayText(string sep) { return Code + sep + Price.ToString("c") + sep + Description; } }
  • 21. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 21 The code for the Book class public class Book : Product { 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; }
  • 22. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 22 The code for the Book class (cont.) set { author = value; } } public override string GetDisplayText(string sep) { return base.GetDisplayText(sep) + " (" + Author + ")"; } }
  • 23. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 23 The code for the Software class public class Software : Product { 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; }
  • 24. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 24 The code for the Software class (cont.) set { version = value; } } public override string GetDisplayText(string sep) { return base.GetDisplayText(sep) + ", Version " + Version; } }
  • 25. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 25 The code for the ProductList class public class ProductList : List<Product> { // Modify the behavior of the Add method of the // List<Product> class public new void Add(Product p) { base.Insert(0, p); } // Provide two additional methods public void Fill() { List<Product> products = ProductDB.GetProducts(); foreach (Product product in products) base.Add(product); } public void Save() { ProductDB.SaveProducts(this); } }
  • 26. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 26 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, System.EventArgs e) { products.Fill(); FillProductListBox(); }
  • 27. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 27 The code for the Product Maintenance form (cont.) private void FillProductListBox() { lstProducts.Items.Clear(); foreach (Product p in products) lstProducts.Items.Add(p.GetDisplayText("t")); } private void btnAdd_Click(object sender, System.EventArgs e) { frmNewProduct newForm = new frmNewProduct(); Product product = newForm.GetNewProduct(); if (product != null) { products.Add(product); products.Save(); FillProductListBox(); } }
  • 28. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 28 The code for the Product Maintenance form (cont.) private void btnDelete_Click(object sender, System.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(); } } }
  • 29. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 29 The code for the Product Maintenance form (cont.) private void btnExit_Click(object sender, System.EventArgs e) { this.Close(); } }
  • 30. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 30 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; }
  • 31. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 31 The code for the New Product form (cont.) private void rbBook_CheckedChanged(object sender, System.EventArgs e) { if (rbBook.Checked) { lblAuthorOrVersion.Text = "Author: "; txtAuthorOrVersion.Tag = "Author"; } else { lblAuthorOrVersion.Text = "Version: "; txtAuthorOrVersion.Tag = "Version"; } txtCode.Focus(); }
  • 32. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 32 The code for the New Product form (cont.) private void btnSave_Click(object sender, System.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(); } }
  • 33. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 33 The code for the New Product form (cont.) private bool IsValidData() { return Validator.IsPresent(txtCode) && Validator.IsPresent(txtDescription) && Validator.IsPresent(txtAuthorOrVersion) && Validator.IsPresent(txtPrice) && Validator.IsDecimal(txtPrice); } private void btnCancel_Click(object sender, System.EventArgs e) { this.Close(); } }
  • 34. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 34 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 Description GetType(fullname) A static method that returns a Type object for the specified name.
  • 35. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 35 Code that uses the Type class to get information about an object Product p; p = new Book("CS10", "Murach's C# 2010", "Joel Murach", 59.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
  • 36. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 36 How to test an object’s type if (p.GetType().Name == "Book") Another way to test an object’s type if (p.GetType() == Type.GetType("ProductMaintenance.Book"))
  • 37. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 37 Two methods that display product information public void DisplayProduct(Product p) { MessageBox.Show(p.GetDisplayText()); } public void DisplayBook(Book b) { MessageBox.Show(b.GetDisplayText()); }
  • 38. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 38 Code that doesn’t require casting Book b = new Book("CS10", "Murach's C# 2010", "Joel Murach", 54.50m); DisplayProduct(b); // Casting is not required because // Book is a subclass of Product. Code that requires casting Product p = new Book("CS10", "Murach's C# 2010", "Joel Murach", 54.50m); DisplayBook((Book)p); // Casting is required because // DisplayBook accepts a Book // object.
  • 39. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 39 Code that throws a casting exception Product p = new Software("NPTK", ".NET Programmer's Toolkit", "4.0", 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("CS10", "Murach's C# 2010", "Joel Murach", 54.50m); DisplaySoftware(p as Software); // Passes null because p isn’t a Software object
  • 40. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 40 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. }
  • 41. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 41 A class that inherits the abstract Product class public class Book : Product { public string Author {get; set; } public override string GetDisplayText(string sep) { return this.Code + sep + this.Description + "( " + this.Author + ")" + sep + this.Price.ToString("c"); } }
  • 42. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 42 The class declaration for a sealed Book class public sealed class Book : Product
  • 43. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 43 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"); } }
  • 44. Murach’s C# 2010, C14 © 2010, Mike Murach & Associates, Inc.Slide 44 How sealed methods work (cont.) 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"); } }