Summary

These lecture notes cover the concepts of inheritance and polymorphism in object-oriented programming. They explore how inheritance allows classes to reuse code and how polymorphism enables methods to have different implementations within derived classes.

Full Transcript

INHERITANCE AND POLYMORPHISM Week 3 - Tuesday Lecture Definition Inheritance enables you to create new classes that reuse, extend, and modify the behavior tha...

INHERITANCE AND POLYMORPHISM Week 3 - Tuesday Lecture Definition Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes. The class whose members are inherited is INHERITANCE called the base class if you have a base class Animal, you might have one derived class that is The class that inherits those members is called named Mammal and another derived the derived class. class Reptile. A Mammal is an Animal, A derived class can have only one direct and a Reptile is an Animal, but each base class. derived class represents different A derived class is a specialization of the specializations of the base class. base class. A=πr2 P=2(l+w) C=2πr A=wl #region Student Fields DEFINING THE BASE CLASS private int studentId; private string gender; #endregion  The base class is defined in the same manner as how you define a normal class - just as you #region Student Property Methods did in the Workshop when defining the  All aspects of the class will be included: class public int StudentId name, fields, constructor etc. { get { return studentId; } set { studentId = value; } } public string Gender { get { return gender; } set { gender = value; } } DEFINING THE BASE CLASS - EXAMPLE You are required to create a program that calculates and displays the appropriate area for each shape (such as Circle, Cylinder, and Sphere) by invoking the appropriate implementation of the Area() method, according to the object that is associated with the method. DEFINING THE DERIVED CLASS  When you define a class to derive from another class, the derived class implicitly gains all the members of the base class, except for its constructors and destructors.  The derived class can thereby reuse the code in the base class without having to re-implement it.  In the derived class, you can add more members.  In this manner, the derived class extends the functionality of the base class. DEFINING THE DERIVED CLASS - EXAMPLE You are required to create a program that calculates and displays the appropriate area for each shape (such as Circle, Cylinder, and Sphere) by invoking the appropriate implementation of the Area() method, according to the object that is associated with the method.  You will notice that the program alerts you to a problem in the derived class.  Put your cursor on the Area Method and you will notice a warning stating that this method hides the inherited Area method of class Shape. These methods also have the WRAPPING UP same name - the plan is the base class to have this method and the derived classes to inherit it and use it as INHERITANCE they please. But currently, the circle class is not able to do that - as per the warning  This is not good because for full inheritance to be realised, we would want to use that base class method.  For us to be able to utilise the power of inheritance to its full potential, we need the third pillar of object-oriented programming - polymorphism. When encapsulation, inheritance and polymorphism work together, we can achieve the best out of OOP. INHERITANCE AND POLYMORPHISM Week 3 - Tuesday Lecture  Polymorphism means "many-shapes" or "many forms"  Occurs when we have many classes that are related to each other by inheritance.  Inheritance lets us inherit fields and methods from another class....  Polymorphism uses those methods to perform different tasks. This allows us to perform a single POLYMORPHISM action in different ways.  Usually referred to as the third pillar of object- oriented programming, after encapsulation and inheritance.  Categories or forms of Polymorphism  Static  Dynamic  The mechanism of linking a function with an object during compile time is called early binding. It is also called static binding - hence static polymorphism.  C# provides two techniques to implement static polymorphism:  Operator overloading - to be discussed in future lectures  Function overloading  You can have multiple definitions for the same function name in POLYMORPHISM the same scope.  The definition of the function must differ from each other by the OPERATOR & FUNCTION OVERLOADING types and/or the number of arguments in the argument list.  In short, function/method overloading means you are defining several versions of the same function/method, so as to avoid having the same code several places. i.e multiple functions/methods can have the same name with different parameters:  Example 1: string Substring (int startIndex) //the Substring() method of the String class string Substring (int startIndex, int length) //the Substring() method of the String class overloaded Example 2: You have already met this kind of polymorphism in the Shape class we implemented earlier... We have two constructors having the same name but with different parameter/arguments as shown below: #region Constructor public Shape() POLYMORPHISM { x = 0; y = 0; OPERATOR & FUNCTION OVERLOADING } public Shape(double myCoordinate1, double myCoordinate2) { x = myCoordinate1; y = myCoordinate2; } #endregion  C# allows you to create abstract classes that are used to provide partial class implementation of an interface.  Implementation is completed when a derived class inherits from it.  Abstract classes contain abstract methods, which are implemented by the derived class.  The derived classes have more specialized functionality.  With abstract classes:−  You cannot create an instance of an abstract class POLYMORPHISM  You cannot declare an abstract method outside an abstract class DYNAMIC POLYMORPHISM How to implement dynamic polymorphism In the base class: When you have a function defined in a class that you want to be implemented in an inherited class(es), you use virtual functions/methods and the call to these functions will be decided at runtime. A virtual method is a method that can be redefined in derived classes. POLYMORPHISM A virtual method has an implementation in a base class as well as derived the class. A virtual method is used when a method's basic DYNAMIC POLYMORPHISM functionality is the same but sometimes more functionality is : VIRTUAL AND OVERRIDEN METHODS needed in the derived class. A virtual method is created in the base class that can be overriden in the derived class. We create a virtual method in the base class using the virtual keyword and that method is overriden in the derived class using the override keyword The virtual keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class. Example Step 1: Given that the implementation of polymorphism requires that the base class implements the virtual method/function; we will use the Shape class. Step 2: In the base class (i.e the Shape class), we can find the Area method as follows: #region Methods public double Area() POLYMORPHISM { return x * y; } DYNAMIC POLYMORPHISM : VIRTUAL AND OVERRIDEN METHODS #endregion Step 3: Given that we want to use this method to calculate the are of the Circle and the other shapes, we need to be able to use this Area method that is in the base class. So we will include the keyword virtual in the method to allow the derived classes to access it as follows: public virtual double Area() //The virtual modifier indicates to derived classes that they can override this method. { return x * y; In the derived class  A derived class inherits most of the data members from the base class.  If we have a virtual method in the base class, we are allowed to inherit from it and change the method implementation to suit what we want. To use that virtual method, you need to have a method in the derived class having the same name. POLYMORPHISM  This method, that has the same name as the virtual method in the base class, must use the override keyword  The override keyword/modifier is required to extend or DYNAMIC POLYMORPHISM : VIRTUAL AND OVERRIDEN METHODS modify the abstract or virtual implementation of an inherited method, property, indexer, or event….thereby providing a new implementation of a member that is inherited from a base class.  The method that is overridden by an override declaration is known as the overridden base method.  The overridden base method must have the same signature as the override method.  The overridden base method must be virtual. Example: Back to our Shape problem: Step 1: Understand why we want to override the base class.  Now that we have the base class having a virtual method, we can modify that method to suit our needs in the derived class. POLYMORPHISM  Currently the base class method uses the following formulae to calculate the area: x*y.  But the formulae for the circle area is πr2. DYNAMIC POLYMORPHISM : VIRTUAL AND OVERRIDEN METHODS  This is why we need to override the virtual method so we can change the implementation Step 2: Currently the Area method in the derived class is as Example: create a program that follows: calculates and displays the public double Area()//customize appropriate area for each shape { (such as Circle, Cylinder, and Sphere) return PI*x*x; by invoking the appropriate } implementation of the Area() So now we will add the override keyword in the code as follows method, according to the object that public override double Area() //customize is associated with the method. { return PI*x*x; } You are now ready for Workshop3  To prepare for the workshop go over the concepts of Inheritance and Polymorphism.  Go over the Shape class again DATABASES Week 4 - Tuesday Lecture LAYERED ARCHITECTURE VARIOUS LAYERS IN THE ARCHITECTURE There are four layers we would like to look into. Presentation responsible for handling all user interface and browser communication logic, Exposed to the end user Application layers can also make it easier to swap out implementations for testing purposes. Instead of having to write tests that operate against the real data layer or UI layer of the application, these layers can be replaced at test time with fake implementations that provide known responses to requests. This typically makes tests much easier to write and much faster to run when compared to running tests against the application's real infrastructure VARIOUS LAYERS IN THE ARCHITECTURE Application logic responsible for executing specific business rules associated with the request the application layer is an excellent way to separate interfacing layers such as presentation and domain. In doing so, the application layer contributes immensely to the clarity of the entire design. The application layer is the additional layer that reports to the presentation and orchestrates any further business action. The application layer is where you orchestrate the implementation of use- cases. In the logic layer, classes decide what information they need in order to solve their assigned problems, request that information from the accessor layer, manipulate that information as required, and return the ultimate results to the presentation layer for formatting. VARIOUS LAYERS IN THE ARCHITECTURE Domain hosts the entire business logic that is not specific to one or more use-cases. Consists of a model (known as the domain model) and possibly a family of services. The nature of the model can vary. Most of the time, it is an entity-relationship model, but it can be made of functions too. Entities in the model are expected to expose both data and behavior. Domain services are pieces of domain logic that, for some reason, don’t fit into any of the existing entities. A domain service is a class, and it groups logically related behaviors that typically operate on multiple domain entities. A domain service often also requires access to the infrastructure layer for read/write operations. The ultimate goal of a domain model is to implement the ubiquitous language and express the actions that business processes require. In this regard, exposing some behavior tends to be more relevant than holding some data. Database /infrastructure The infrastructure layer is anything related to using concrete technologies The most prominent component of the infrastructure layer is the persistence layer— data access layer The persistence layer knows how to read and/or save data. IMPLEMENTING THE LAYERED ARCHITECTURE We will use the separation of concern principle + encapsulation + the other three pillars that come with OOP. Presentation layer We will have the GUI here - for the various controls required Boundary Classes - responsible for presenting information to the user and interpreting user commands. Application logic We will have control classes. These classes will coordinate the application activity. It doesn't contain any business logic. It does not hold the state of business objects, but it can hold the state of an application task's progress. Domain layer We will have entity classes The classes will contain information about the business domain - Information about the business use case and the business rules. Domain objects encapsulate the state and behaviour of business entities. Database We will have the LocalDB with the various entities - already set up in Workshop 4 The data source here ACTIVEX DATA OBJECTS (ADO) A set of classes that expose data access services to the.NET programmer. A programming interface to access data in a database. Provides consistent access to data sources such as Microsoft® SQL Server™, as well as data sources exposed through OLE DB and XML. Data-sharing consumer applications can use ADO.NET to connect to these data sources and retrieve, manipulate, and update data. Provides a rich set of components for creating distributed, data- sharing applications. It is an integral part of the.NET Framework, providing access to relational data, XML, and application data. Supports a variety of development needs, including the creation of front-end database clients and middle-tier business objects used by applications, tools, languages, or Internet browsers. ADO.NET COMPONENTS Data providers: a set of components, such as Connection Dataset Objects COPY Disconnected from data source Can be populated with data from many sources A DataSet represents an in-memory database A DataSet is a set of DataTable objects A DataAdapter is used to retrieve data from a data source and populate tables within a DataSet. resolves changes made to the DataSet back to the data source. It uses the Connection object of the.NET Framework data provider to connect to a data source, It uses Command objects to retrieve data from and resolve changes to the data source NAMESPACES Definition A namespace can be seen as a container for some classes in much the same way that a folder on your file system contains files. Namespaces are C# program elements designed to help you organize your programs and assist in avoiding name clashes between two sets of code. For more on namespaces, see Namespaces Namespaces required with working with databases The System.Data namespace provides access to classes that represent the ADO.NET architecture that lets you build components that efficiently manage data from multiple data sources. The Sqlconnection class represents an open connection to a SQL Server database. It is used together with SqlDataAdapter and SqlCommand to increase performance when connecting to a Microsoft SQL Server database. For more, see the SqlConnectionClass File NAMESPACES SqlCommand Class The SqlCommand class is at the heart of the System.SqlClient namespace. It is used to execute operations on a database and retrieve data (CRUD). In the database programming, there are four basic and essential operations: create, read, update, and delete. These operations in database programming are called CRUD operations. CRUD is an acronym of the CREATE, READ, UPDATE and DELETE words. CREATE – insert row/rows to table. READ – read (select) row/rows from a table. UPDATE – edit row/rows in the table. DELETE – delete row/rows in the table. In short: a SqlCommand object allows you to specify what type of interaction you want to perform with a database. For example, you can do select, insert, modify, and delete commands on rows of data in a database table. See the Properties and Methods of the SqlCommand Class here. For more information read the attached file SqlCommandObjectFile NAMESPACES The System.Data.SqlClient namespace is the.NET Data Provider for SQL Server. contains the provider-specific ADO.NET objects used to connect to a SQL Server 7 or SQL Server 2000 database, execute a command, and transfer information to and from a DataSet. Interacts with SQL Server to allow the development of data-driven applications. It creates database connections with SqlConnection. It inserts data with SqlCommand. Handles rows with SqlDataReader.  A database is made up of a collection of tables that stores a specific set of structured data.  A table contains a collection of rows/tuples and column/ attributes  Each column/ attributes in the table is designed to store a certain type of information, for example, dates, names, dollar amounts, and numbers. DATABASE  For more, please visit INF2007 resources or your previous database related course.  One way to communicate with a relational database that lets you define, query, modify, and control the data is by using the SQL (Structured Query Language)  SQL consists of various command languages such as:  Data Definition Language (DDL) which are SQL commands that can be used to define the database schema..... create and modify the structure of database DATABASE AND THE objects in the database.  Examples of DDL commands include: STRUCTURED QUERY  CREATE – is used to create the database or its objects (like table, index, function, views, store procedure LANGUAGE and triggers).  DROP – is used to delete objects from the database.  ALTER-is used to alter the structure of the database.  A schema is the collection of multiple database objects, which are known as schema objects. Examples include:  a Table - to store data;  a View - to project data in a desired format from one or more tables  SQL consists of various command languages such as: DATABASE AND THE  Data Manipulation Language (DML) - a vocabulary used to retrieve and work with data in SQL Server and SQL STRUCTURED QUERY Database. Examples include  INSERT – is used to insert data into a table. LANGUAGE  UPDATE – is used to update existing data within a table.  DELETE – is used to delete records from a database table.  As a database, we will use the LocalDB:  LocalDB can act as an embedded database for a small application  LocalDB is a developer oriented, on-demand managed instance of the SQL Server engine that can be turned on DATABASE AND THE automatically when needed and turned off when not in use. STRUCTURED QUERY  It requires no configuration to run and allows for quick access to a database engine without the overhead of LANGUAGE managing and installing a full SQL Server instance.  LocalDB utilizes the minimal amount of files needed to achieve all of this.  Having the database access stay local greatly reduces the complexity for developing and testing applications with a SQL Server backend. COLLECTIONS AND ADO.NET Week 5 - Tuesday Lecture For many applications, you want to create and manage groups of related objects. COLLECTIONS MSDN There are two ways to group objects: by creating arrays of objects, and by creating collections of objects. Collections provide a more flexible way to work with groups of objects Collections are classes, specialized classes for data storage and retrieval. Collection classes serve various purposes, such as COLLECTIONS allocating memory dynamically to elements and accessing a list of items on the basis of an index etc. A collection class contains methods to: Add; Remove; Navigate; Search for objects…  To use collections, you can use one of the classes in the System.Collections.Generic namespace.  These classes contains interfaces and classes that define generic collections, which allow users to create strongly typed collections that provide better type safety and performance than non-generic strongly typed collections.  You will also need the System.Collections.ObjectModel namespace IMPLEMENTING A  which contains classes that can be used as collections in the object model of a reusable library. Use these classes when COLLECTION properties or methods return collections. ------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System; using System.Collections.Generic; using System.Collections.ObjectModel; public class Demo { public static void Main() { Collection dinosaurs = new Collection(); dinosaurs.Add("Psitticosaurus"); dinosaurs.Add("Caudipteryx"); dinosaurs.Add("Compsognathus"); dinosaurs.Add("Muttaburrasaurus"); Console.WriteLine("{0} dinosaurs:", dinosaurs.Count); Display(dinosaurs); https://docs.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.collection-1.add?view=netcore-3.1 Looks like Arrays right: - But... Arrays are fixed in size. Collections are variable in size, thereby providing a more flexible way of working with a group of objects. In arrays, you would have noticed that you need to define the number of elements in an array COLLECTIONS beforehand. This had to be done when the array was declared. But in a collection, you don't need to define the size of the collection beforehand. You can add elements or even remove elements from the collection at any point of time. COMMUNICATING WITH THE DATABASE CRUD Commands RULES FOR AUTOMATICALLY GENERATED COMMANDS Command Rule InsertCommand Inserts a row at the data source for all rows in the table with a RowState of Added. Inserts values for all columns that are updateable (but not columns such as identities, expressions, or timestamps). UpdateCommand Updates rows at the data source for all rows in the table with a RowState of Modified. Updates the values of all columns except for columns that are not updateable, such as identities or expressions. Updates all rows where the column values at the data source match the primary key column values of the row, and where the remaining columns at the data source match the original values of the row. For more information, see "Optimistic Concurrency Model for Updates and Deletes," later in this topic. DeleteCommand Deletes rows at the data source for all rows in the table with a RowState of Deleted. Deletes all rows where the column values match the primary key column values of the row, and where the remaining columns at the data source match the original values of the row. For more information, see "Optimistic Concurrency Model for Updates and Deletes," later in this topic. CRUD Commands InsertCommand Inserts a row at the data source for all rows in the table with a RowState of Added. Inserts values for all columns that are updateable (but not columns such as identities, expressions, or timestamps). Gets the state of a DataRow object. Commits all the changes made to this row since the last time AcceptChanges() was called. BUILD PARAMETERS, CREATE COMMANDS & UPDATE DATABASE We will use command objects to talk to our data source Command objects use parameters to pass values to SQL statements, providing type checking and validation. The syntax for parameter placeholders depends on the data source. The.NET Framework data providers handle naming and specifying parameters and parameter placeholders differently. This syntax is customized to a specific data source, as described in theParameter Data provider following table. naming syntax System.Data.SqlClient Uses named parameters in the format @parametername. System.Data.OleDb Uses positional parameter markers indicated by a question mark (?). System.Data.Odbc Uses positional parameter markers indicated by a question mark (?). System.Data.OracleClient Uses named parameters in the format :parmname (or parmname). BUILD PARAMETERS, CREATE COMMANDS & UPDATE DATABASE See Configuring parameters and parameter data types BUILD PARAMETERS, CREATE COMMANDS & UPDATE DATABASE Introduction to OOP Week 2 ABSTRACTION: CLASSES AND OBJECTS Classes: Classes are the main focus in Object oriented programming (OOP).  A class is like a blueprint of a specific object.  A class is a collection of objects of similar type.  A class is a model for creating objects. Objects: an instance of a class, and the process of creating an object is called instantiation.  What that means is that ⇒ an Object is an actual physical existence of a Class. It is a real entity whose structure, identity and behavior are decided by a Class.  An object is a block of memory that has been allocated and configured according to the blueprint.  Blueprint: An object is a combination of data/fields and methods.  Fields are actual variables in your object that stores a particular piece of information.  The data and the methods are called members of an object.  These objects communicate together through methods - actions they perform.  Each object can receive messages, send messages and process data.  A program may create many objects of the same class.  Objects are also called instances, and they can be stored in either a named variable or in an array or collection  Creating an object means allocating memory to store the data of variables temporarily. i.e. we create an object of class to store data temporarily. Examples If a class can be defined as a template/blueprint that describes the behavior/state that an object of its type support - what does this mean?  If we consider the real-world, we can find many objects around us, cars, dogs, humans, etc.  All these objects have a state and a behavior.  If we consider a dog, then its state or characteristics/attributes include - name, breed, color.  If we consider a dog, then its behavior is - barking, wagging the tail, running  If we consider an Employee: the state/fields/ characteristics/attributes include Name, Id, Salary etc respectively.  If we consider a Car as a class then examples of objects of this car include Toyota, Nissan, Audi, Golf etc  If we consider a Car as a class then: state/fields/ characteristics/attributes include wheels, doors, seating capacity.  If we consider a Car as a class then its behavior is: accelerate, stop, display how much fuel is left etc. Consider the following code to demonstrate how to define a class namespace ProductMaintenance { public class Product { private string code; private string description; private decimal price; public Product(){} public Product(string code, string description, decimal price) In short, a class has: Accessibility level - please visit INF1003. Class name Fields: actual variables in your object that stores a particular piece of information, Properties and Methods/ functions Summary on classes Software objects have a state and a behavior. A software object's state is stored in fields and behavior is shown via methods. Methods operate on the internal state of an object and the object-to-object communication is done via methods. A good rule of thumb to identify classes in Object Oriented programming is that: Classes are the Nouns in your analysis of the problem Methods in an class correspond to the Verbs that the noun does Properties are the Adjectives that describe the noun ABSTRACTION: CLASSES AND OBJECTS Abstraction  Abstraction is a principle of object-oriented programming language (OOP)  The word abstract means a concept or an idea not associated with any specific instance  It is used to hide the implementation details and display only essential features of the object. i.e allows making relevant information visible ABSTRACTION: CLASSES AND Abstraction OBJECTS  It is a process of abstracting or hiding the functionality.....making classes not associated with any specific instance ~object  eg: for the method Console.WriteLine(), no one knows what actually is happening behind the function calling. We are just using it by calling and passing the arguments. This is the thing called Abstraction.  Abstraction is needed when we need to only inherit from a certain class, but do not need to instantiate objects of that class. In such a case the base class can be regarded as "Incomplete". Such classes are known as an "Abstract Base Class". How to implement abstraction in c#  Use the keyword Abstract ABSTRACTION: CLASSES AND OBJECTS  Once a class has been declared as an Abstract class, it cannot be instantiated; it means the object of that class cannot be created.