Interfaces and Generics

Slides:



Advertisements
Similar presentations
Generics, Lists, Interfaces
Advertisements

CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek.
Interfaces CSC 171 FALL 2004 LECTURE 14. Project 1 review public class Rational { private int numerator, denominator; public Rational(int numerator, int.
Language Fundamentals in brief C# - Introduction.
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
Encapsulation, Inheritance & Interfaces CSE 115 Spring 2006 February 27, March 1 & 3, 2006.
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 3rd Edition.
5. OOP. 2 Microsoft Objectives “Classes, objects and object-oriented programming (OOP) play a fundamental role in.NET. C# features full support for the.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
BIM313 – Advanced Programming Techniques Object-Oriented Programming 1.
Copyright © 2006 Thomas P. Skinner1 Chapter 5 Indexers, Interfaces, and Enumerators.
FEN 2012 UCN Technology: Computer Science1 C# - Introduction Language Fundamentals in Brief.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
Modern Software Development Using C#.NET Chapter 5: More Advanced Class Construction.
Advanced C# Types Tom Roeder CS fa. From last time out parameters difference is that the callee is required to assign it before returning not the.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Chapter 6 Interfaces. Class Status CU will be close for winter break from Dec. 22. till Jan.2 We have 3 classes left after tonight (Jan 8,15, and 22)
Introduction to C# 2.0 An Advanced Look Adam Calderon Principal Engineer - Interknowlogy Microsoft MVP – C#
PROGRAMMING IN C#. Collection Classes (C# Programming Guide) The.NET Framework provides specialized classes for data storage and retrieval. These classes.
Generics Generics vs. heterogeneous collections Doing your own generics FEN 2014UCN Teknologi/act2learn1.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
Murach's C# 2012, C15© 2013, Mike Murach & Associates, Inc.Slide 1.
Lecture 5:Interfaces and Abstract Classes
Chapter 7: Cloning and RTTI
Introduction to LINQ and Generic Collections
Advanced Object-Oriented Programming Features
2.7 Inheritance Types of inheritance
How to work with indexers, delegates, events, and operators
IST311 / 602 Cleveland State University – Prof. Victor Matos
Jim Fawcett CSE681 – Software Modeling and Analysis Fall 2005
Chapter 8 Classes and Objects
Iterators and Comparators
Chapter 5: Programming with C#
How to Create and use Classes and Structures
How to work with indexers, delegates, events, and operators
5.1 Being Objects and A Glimpse into Coding
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
Interface.
Programming in C# Comparison (Sorting)
Conditional Statements
Visual C# 2005: Language Enhancements
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Chapter 8: User-Defined Classes and ADTs
How to Create and use Classes and Structures
Generics in C# / Anders Børjesson
User-Defined Classes and ADTs
Interfaces and Generics
Getting Ready for Visual Studio 2005
Chapter 8 Classes User-Defined Classes and ADTs
Tonga Institute of Higher Education
How to organize and document your classes
Chapter 14 Abstract Classes and Interfaces
CIS 199 Final Review.
IST311 / 602 Cleveland State University – Prof. Victor Matos
Chapter 8 Class Inheritance and Interfaces
Review of Previous Lesson
Based on Murach (ch 14) and Deitel 2012
Object oriented programming (OOP) Lecture No. 6
CMPE212 – Reminders Assignment 2 due next Friday.
Review for Midterm 3.
Advanced .NET Programming I 3rd Lecture
Chengyu Sun California State University, Los Angeles
5. OOP OOP © 2003 Microsoft.
Visual C# 2005: Language Enhancements
Presentation transcript:

Interfaces and Generics Based on Murach (ch 15) and Deitel slides

Objectives Applied Use .NET interfaces as you develop the classes for an application. Develop and use your own interfaces. Knowledge Distinguish between an interface and an abstract class. Describe the use of the .NET ICloneable IComparable<> IEnumerable<> interfaces. In general terms, describe the use of generic interfaces. `

The IDisplayable interface interface IDisplayable { string GetDisplayText(string sep); }

A Product class that implements the IDisplayable interface public class Product : IDisplayable { public string Code { get; set; } public string Description { get; set; } public decimal Price { get; set; } public Product(string Code, string Description, decimal Price) this.Code = Code; this.Description = Description; this.Price = Price; } public string GetDisplayText(string sep) => this.Code + sep + this.Description + sep + this.Price.ToString("c");

Code that uses the IDisplayable interface IDisplayable product = new Product( "CS15", "Murach's C# 2015", 56.50m); Console.WriteLine(product.GetDisplayText("\n")); Can be used

A comparison of interfaces and abstract classes Both interfaces and abstract classes provide signatures for properties and methods that a class must implement. All of the members of an interface are abstract. In contrast, an abstract class can implement some or all of its members. A class can inherit only one class (including abstract classes), but a class can implement more than one interface. Interfaces can’t declare static members, but abstract classes can.

Commonly used .NET interfaces Business classes need to implement it

Common .NET interfaces for collections

The syntax for creating an interface public interface InterfaceName { type MethodName(parameters); type Property Name { [get;] [set;] } ... } Unlike classes NO implementation NO access modifiers (all public) NO static

An interface that defines one method public interface IDisplayable { string GetDisplayText(string sep); } An interface that defines 2 methods and 1 property public interface IPersistable object Read(string id); bool Save(object o); bool HasChanges get; set;

The syntax for creating an interface that inherits other interfaces public interface InterfaceName : InterfaceName1 [, InterfaceName2]... { interface members... } Example: an interface that inherits two interfaces public interface IDataAccessObject : IDisplayable, IPersistable // add additional members here

The syntax for implementing an interface Class is first public class ClassName : [BaseClassName,] InterfaceName1[, InterfaceName2]... A Product class that implements ICloneable public class Product : ICloneable A Product class that implements two interfaces public class Product : ICloneable, IDisplayable A class that inherits a class and implements two interfaces public class Book : Product, ICloneable, IDisplayable

Peek Definition

The code that’s generated when you implement the interface public object Clone() { throw new NotImplementedException(); } The code that’s generated when you explicitly implement the interface object ICloneable.Clone()

The code for the cloneable Product class public class Product : IDisplayable, ICloneable { public string Code { get; set; } public string Description { get; set; } public decimal Price { get; set; }   public Product(string Code, string Description, decimal Price) this.Code = Code; this.Description = Description; this.Price = Price; } public string GetDisplayText(string sep) => this.Code + sep + this.Description + sep + this.Price.ToString("c");

The code for the cloneable Product class cont. public object Clone() { Product p = new Product(); p.Code = this.Code; p.Description = this.Description; p.Price = this.Price; return p; }  

Code that creates and clones a Product object Product p1 = new Product("BJWN", "Murach's Beginning Java with NetBeans",57.50m); Product p2 = (Product)p1.Clone(); //Clone returns object p2.Code = "BJWE"; //modifying Description p2.Description = "Murach's Beginning Java with Eclipse"; Console.WriteLine(p1.GetDisplayText("\n") + "\n"); Console.WriteLine(p2.GetDisplayText("\n") + "\n"); The output BJWN Murach's Beginning Java with NetBeans $57.50   BJWE Murach's Beginning Java with Eclipse

Shallow and Deep Clone Copy Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements. Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.

Using an interface as a parameter A CreateList method that uses an interface as a parameter public static List<object> CreateList(ICloneable obj,int count) { List<object> objects = new List<object>(); for (int i = 0; i < count; i++) object o = obj.Clone(); objects.Add(o); } return objects; A WriteToConsole method that uses an interface as a parameter public static void WriteToConsole(IDisplayable d) => Console.WriteLine(d.GetDisplayText("\n") + "\n");

Code that uses these methods Product product = new Product("CS15","Murach's C# 2015",56.50m); List<object> products = CreateList(product, 3); foreach (Product p in products) { WriteToConsole(p); } The output that’s displayed CS15 Murach's C# 2015 $56.50

Generics, CustomList ex. Data Type (can be any letter) public class CustomList<T> { private List<T> list = new List<T>();   // an Add method public void Add(T item) => list.Add(item); // a read-only indexer public T this[int i] => list[i]; // a read-only property public int Count => list.Count;

Generics, CustomList ex. cont. // the ToString method public override string ToString() { string listString = ""; for (int i = 0; i < list.Count; i++) listString += list[i].ToString() + "\n"; } return listString;

Code that uses the CustomList<> class // Test 1 Console.WriteLine("List 1 - ints"); CustomList<int> list1 = new CustomList<int>(); int i1 = 11; int i2 = 7; list1.Add(i1); list1.Add(i2); Console.WriteLine(list1.ToString());   // Test 2 Console.WriteLine("List 2 - Products"); CustomList<Product> list2 = new CustomList<Product>(); Product p1 = new Product("VB15", "Murach's Visual Basic 2015", 56.50m); Product p2 = new Product("CS15", "Murach's C# 2015", 56.50m); list2.Add(p1); list2.Add(p2); Console.Write(list2.ToString());

Output that results from the Test 1 and Test 2 code List 1 - ints 11 7   List 2 - Products VB15 Murach's Visual Basic 2015 $56.50 CS15 Murach's C# 2015 $56.50

A common generic .NET interface Compare with A common regular .NET interface

Common .NET interfaces for generic collections

Common .NET interfaces for generic collections cont.

A class that implements the IComparable<> interface public class Product : IComparable<Product> { public string Code { get; set; } public string Description { get; set; } public decimal Price { get; set; }   // other members public int CompareTo(Product other) => this.Code.CompareTo(other.Code); } Only Code matters, alphanumeric comparison

Code that uses the class Product : IComparable<> Product p1 = new Product("VB15", "Murach's Visual Basic 2015", 56.50m); Product p2 = new Product("CS15", "Murach's C# 2015", 56.50m); int compareValue = p1.CompareTo(p2); if (compareValue > 0) Console.WriteLine("p1 is greater than p2"); else if (compareValue < 0) Console.WriteLine("p1 is less than p2"); else if (compareValue == 0) Console.WriteLine("p1 is equal to p2");

Values that can be returned by the CompareTo method Value Meaning -1 The current element is less than the compare element. 0 The current element is equal to the compare element. 1 The current element is greater than the compare element. Ex.: Product 1 - Code VB15 Product 2 - Code CS15 Product1 > Product2

Ascii

A class that uses constraints https://msdn. microsoft public class CustomList<T> where T: class, IComparable<T> { private List<T> list = new List<T>(); // an Add method that keeps the list sorted public void Add(T item) if (list.Count == 0) //first item list.Add(item); } else for (int i = 0; i < list.Count; i++) T currentItem = list[i]; T nextItem = null; Classes that implement IComparable sorting

A class that uses constraints cont. if (i < list.Count - 1) { nextItem = list[i + 1]; } int currentCompare =currentItem.CompareTo(item); if (nextItem == null) if (currentCompare >= 0) list.Insert(i, item); // insert before current item break; ...

Keywords that can be used to define constraints Keyword Description class The type argument must be a class. struct The type argument must be a structure other than one that defines a nullable type. new() The type argument must have a default constructor. You can’t use this keyword when the type argument must be a structure. A class that’s constrained to value types public class StructList<T> where T: struct Another class that uses constraints public class ProductList<T> where T: Product, IComparable<T>, new()

A class that implements IEnumerable<> Therefore you can use foreach public class CustomList<T> : IEnumerable<T> { private List<T> list = new List<T>();   // other members   //generic public IEnumerator<T> GetEnumerator() foreach (T item in list) yield return item; }   //regular, not implemented System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() throw new NotImplementedException(); } 

yeld http://stackoverflow.com/questions/39476/what-is- the-yield-keyword-used-for-in-c https://www.youtube.com/watch?v=F7L9seU_mak https://www.youtube.com/watch?v=4fju3xcm21M

Code that uses the class Product p1=new Product("VB15","Murach's Visual Basic 2015",56.50m); Product p2 = new Product("CS15","Murach's C# 2015",56.50m); CustomList<Product> list = new CustomList<Product>(); list.Add(p1); list.Add(p2); foreach (Product p in list) { Console.WriteLine(p.ToString()); }

interface IGenericPersistable<T> { T Read(string id); DB is coming! An interface named IGenericPersistable<> that uses generics Standard way for a business object to read itself from or write itself to a data such as a database. interface IGenericPersistable<T> { T Read(string id); bool Save(T obj); bool HasChanges get; set; }

A class that implements IGenericPersistable<> class Customer : IGenericPersistable<Customer> {   // other members public Customer Read(string id) throw new NotImplementedException(); } public bool Save(Customer obj)

A class that implements IGenericPersistable<> public bool HasChanges { get throw new NotImplementedException(); } set  

Exercise 15-1 Implement the ICloneable interface Add code to a Customer class so it implements the ICloneable interface. Then, create a List<> that contains the requested number of clones and display the clones in a list box.

Project 3-5 Maintain student scores (Student class) Develop an application that maintains a list of student scores using a Student class. This class will implement the ICloneable interface and the Clone method will implement a deep copy.

Project 3-6 Translate English to Pig Latin or Pig Greek Create a form that converts a text entry to Pig Latin or Pig Greek. To do that, you’ll create an interface named ITranslator and two classes that provide the translations by implementing this interface.