Object Oriented Concepts

Slides:



Advertisements
Similar presentations
CSE 1302 Lecture 8 Inheritance Richard Gesick Figures from Deitel, “Visual C#”, Pearson.
Advertisements

Object-Oriented Application Development Using VB.NET 1 Chapter 8 Understanding Inheritance and Interfaces.
C++ Inheritance Systems Programming.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
 2006 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Inheritance.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 17 – Payroll Application: Introducing Inheritance.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
C++ Polymorphism Systems Programming. Systems Programming: Polymorphism 2   Polymorphism Examples   Relationships Among Objects in an Inheritance.
Java™ How to Program, 9/e Presented by: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and.
Unit 5 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
 Simple payroll application that polymorphically calculates the weekly pay of several different types of employees using each employee’s Earnings method.
Cpt S 122 – Data Structures Polymorphism
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
 2005 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Inheritance.
Lecture 8 Inheritance Richard Gesick. 2 OBJECTIVES How inheritance promotes software reusability. The concepts of base classes and derived classes. To.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
 2009 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Inheritance.
Object Oriented Concepts Classes II. Object Oriented concepts Encapsulation Composition Inheritance Polymorphism.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Lecture 9 Polymorphism Richard Gesick.
1 Object-Oriented Programming: Polymorphism 10.1 Introduction 10.2 Relationships Among Objects in an Inheritance Hierarchy Invoking Superclass Methods.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
More on Object-Oriented Programming: Inheritance 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Object Oriented Software Development
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
 2006 Pearson Education, Inc. All rights reserved Polymorphism, Interfaces & Operator Overloading.
 All calls to method toString and earnings are resolved at execution time, based on the type of the object to which currentEmployee refers.  Known as.
 2006 Pearson Education, Inc. All rights reserved Polymorphism, Interfaces & Operator Overloading.
Java Programming Dr. Randy Kaplan. Abstract Classes and Methods.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
1 The finalize, clone, and getClass Methods  The finalize method is invoked by the garbage collector on an object when the object becomes garbage.  The.
Object Oriented Programming
 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Polymorphism.
Introduction to Object-Oriented Programming Lesson 2.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
 2009 Pearson Education, Inc. All rights reserved Polymorphism, Interfaces & Operator Overloading.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
Inheritance ndex.html ndex.htmland “Java.
Object-Oriented Programming: Inheritance and Polymorphism.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
 2006 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Polymorphism.
C++ How to Program, 7/e. © by Pearson Education, Inc. All Rights Reserved.2.
1 Inheritance One of the goals of object oriented programming is code reuse. Inheritance is one mechanism for accomplishing code reuse. It allows us to.
C++ How to Program, 7/e.  There are cases in which it’s useful to define classes from which you never intend to instantiate any objects.  Such classes.
Part -1 © by Pearson Education, Inc. All Rights Reserved.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Polymorphism, Interfaces & Operator Overloading
Object-Oriented Programming: Inheritance
Object-Oriented Programming: Inheritance
Polymorphism, Interfaces & Operator Overloading
Object-Oriented Programming: Polymorphism
Lecture 23 Polymorphism Richard Gesick.
Object-Oriented Programming: Polymorphism
Chapter 9 Object-Oriented Programming: Inheritance
Lecture 22 Inheritance Richard Gesick.
Object-Oriented Programming: Inheritance
Polymorphism and Type Casting
Object-Oriented Programming: Inheritance and Polymorphism
Fundaments of Game Design
Lecture 6 Inheritance CSE /26/2018.
Abstract Classes and Interfaces
Fundaments of Game Design
CIS 199 Final Review.
Presentation transcript:

Object Oriented Concepts Classes II Object Oriented Concepts

Object Oriented concepts Encapsulation Composition Inheritance Polymorphism

Encapsulation Classes normally hide the details of their implementation from their clients. This is called information hiding. The client cares about what functionality a class offers, not about how that functionality is implemented. This concept is referred to as data abstraction. C# provides this object oriented concept with properties.

Composition A class can have references to objects of other classes as members. This is called composition and is sometimes referred to as a has-a relationship One form of software reuse is composition Example: Employee object using Date object for hire date See composition.cs

Inheritance Base class Derived classes Another form of software reuse is inheritance Inheritance allows a new class to absorb an existing class’s members. A derived class normally adds its own fields and methods to represent a more specialized group of objects. The is-a relationship represents inheritance. Examples: Base class Derived classes Student GraduateStudent, UndergraduateStudent Shape Circle, Triangle, Rectangle Loan CarLoan, HomeImprovementLoan, MortgageLoan Employee Faculty, Staff, HourlyWorker, CommissionWorker BankAccount CheckingAccount, SavingsAccount

Base and Derived Classes in C# Objects of all classes that extend a common base class can be treated as objects of that base class. A base class’s private members are not directly accessible by derived-class methods and properties. A base class’s protected members can be accessed by members of both that base class and of its derived classes. A base class’s protected internal members can be accessed by members of a base class, the derived classes and by any class in the same assembly. If a class does not specify that it inherits from another class, it implicitly inherits from object. public class CommissionEmployee : object

Base and Derived Classes in C# The derived class can override the base-class method. To override a base-class method, a derived class must declare a method with keyword override . public override string ToString() A constructor initializer with keyword base invokes the base-class constructor. See example BasePlusCommissionEmployee The virtual and abstract keywords are required in a base-class method so that the derived classes can override it. Using protected instance variables creates several potential problems. The derived-class object can set an inherited variable’s value directly without validity checking. Derived-class methods would need to be written to depend on the base class’s data implementation. You should be able to change the base-class implementation while still providing the same services to the derived classes.

Base and Derived Classes in C# The derived-class constructor, before performing its own tasks, invokes its direct base class’s constructor. This is done either explicitly or implicitly. When a base-class method is overridden in a derived class, if the derived-class version wants to call the base-class version, it uses base keyword. public override decimal Earnings() { return BaseSalary + base.Earnings(); } // end method Earnings

System.Object All classes inherit directly or indirectly from the object class. Figure below summarizes object’s methods: Method Description Equals This method compares two objects for equality and returns true if they are equal and false otherwise. Finalize Finalize is called by the garbage collector before it reclaims an object’s memory. GetHashCode The hashcode value returned can be used by a hashtable to determine the location at which to insert the corresponding value. GetType Returns an object of class Type that contains information about the object’s type. MemberwiseClone This protected method makes a copy of the object on which it is called. Instance-variable values in one object are copied into another object of the same type. For reference types, only the references are copied. ReferenceEquals This static method returns true if two objects are the same instance or if they are null references. ToString Returns a string representation of an object. The default implementation returns the namespace and class name.

Polymorphism Polymorphism enables you to write applications that process objects that share the same base class in a class hierarchy as if they were all objects of the base class. If class Rectangle is derived from class Quadrilateral, then a Rectangle is a more specific version of a Quadrilateral. Any operation that can be performed on a Quadrilateral object can also be performed on a Rectangle object. These operations also can be performed on other Quadrilaterals, such as Squares, Parallelograms and Trapezoids. The polymorphism occurs when an application invokes a method through a base-class variable.

Polymorphism An object of a derived class can be treated as an object of its base class. When the compiler encounters a method call made through a variable, it determines if the method can be called by checking the variable’s class type. At execution time, the type of the object to which the variable refers determines the actual method to use. See example: polymorphism virtual, override and new keywords http://msdn.microsoft.com/en-us/library/6fawty39(VS.80).aspx

as / is operators When downcasting an object, a System.InvalidCastException occurs if at execution time the object does not have an is-a relationship with the type specified in the cast operator. An object can be cast only to its own type or to the type of one of its base classes. You can avoid a potential InvalidCastException by using the as operator to do a downcast rather than a cast operator. If the downcast is invalid, the expression will be null instead of throwing an exception. Before performing a cast from a base-class object to a derived- class object, use the is operator to ensure that the object is indeed an object of an appropriate derived-class type.

Abstract Classes Abstract classes, or abstract base classes cannot be used to instantiate objects. Abstract base classes are too general to create real objects—they specify only what is common among derived classes. Classes that can be used to instantiate objects are called concrete classes. Concrete classes provide the specifics that make it reasonable to instantiate objects. An abstract class normally contains one or more abstract methods, which have the keyword abstract in their declaration. A class that contains abstract methods must be declared as an abstract class even if it contains concrete (nonabstract) methods. Abstract methods do not provide implementations. Constructors and static methods cannot be declared abstract .

Abstract Classes abstract property declarations have the form: public abstract PropertyType MyProperty { get; set; } // end abstract property An abstract property may omit implementations for the get accessor, the set accessor or both. Concrete derived classes must provide implementations for every accessor declared in the abstract property.

Case Study: Payroll System Using Polymorphism In this example, we create an enhanced employee hierarchy to solve the following problem: A company pays its employees on a weekly basis. The employees are of four types: Salaried employees are paid a fixed weekly salary regardless of the number of hours worked, hourly employees are paid by the hour and receive overtime pay for all hours worked in excess of 40 hours, commission employees are paid a percentage of their sales, and salaried-commission employees receive a base salary plus a percentage of their sales. For the current pay period, the company has decided to reward salaried- commission employees by adding 10% to their base salaries.

Payroll System Using Polymorphism We use abstract class Employee to represent the general concept of an employee. SalariedEmployee, CommissionEmployee and HourlyEmployee extend Employee. Class BasePlusCommissionEmployee—which extends CommissionEmployee—represents the last employee type. Let’s look at the example code: PayrollSystem solution Figure | Employee hierarchy UML class diagram

Interfaces Interfaces define and standardize the ways in which people and systems can interact with one another. A C# interface describes a set of methods that can be called on an object—to tell it, for example, to perform some task or return some piece of information. An interface declaration begins with the keyword interface and can contain only abstract methods, properties, indexers and events. All interface members are implicitly declared both public and abstract. An interface can extend one or more other interfaces to create a more elaborate interface that other classes can implement.

Interfaces An interface is typically used when disparate (i.e., unrelated) classes need to share common methods so that they can be processed polymorphically A programmer can create an interface that describes the desired functionality, then implement this interface in any classes requiring that functionality. An interface often is used in place of an abstract class when there is no default implementation to inherit—that is, no fields and no default method implementations. Like abstract classes, interfaces are typically public types, so they are normally declared in files by themselves with the same name as the interface and the .cs file-name extension.

Interface Example: IPayable To build an application that can determine payments for employees and invoices alike, we first create an interface named IPayable. Interface IPayable contains method GetPaymentAmount that returns a decimal amount to be paid for an object of any class that implements the interface. By convention, the name of an interface begins with "I". This helps distinguish interfaces from classes, improving code readability. When a class implements an interface, the same is-a relationship provided by inheritance applies. Example: IPayable solution

Multiple Inheritance Not supported in classes, but supported via interfaces To implement more than one interface, use a comma- separated list of interface names after the colon (:) in the class declaration. Example: public abstract class Array : ICloneable, IList, ICollection, IEnumerable

Common Interfaces of the .NET Framework Class Library

sealed Methods and Classes A method declared sealed in a base class cannot be overridden in a derived class. Methods that are declared private are implicitly sealed. Methods that are declared static also are implicitly sealed, because static methods cannot be overridden either. A derived-class method declared both override and sealed can override a base-class method, but cannot be overridden in classes further down the inheritance hierarchy.

Operator Overloading Just like methods, we can override operators to give them new meanings (e.g. + addition) We use the operator keyword Operator methods need to be static Operator methods need to take at least one parameter Operator methods could be overloaded too (multiple operator methods can exist) Let’s see an example: ComplexNumber

Extension Methods Used to add functionality to an existing class without modifying the class’s source code. See example ExtensionMethods.sln The this keyword before a method’s first parameter notifies the compiler that the method extends an existing class. An extension method is called on an object of the class that it extends as if it were a members of the class. The compiler implicitly passes the object that is used to call the method as the extension method’s first argument. The type of an extension method’s first parameter specifies the class that is being extended—extension methods must define at least one parameter. Extension methods must be defined as static methods in a static top-level class.

struct (structure) struct is very similar to a class Like classes, struct’s can have methods and properties with access modifiers. Struct members are accessed via (.) operator similarly. So they are almost the same with one difference: Class is a reference type whereas struct is a value type. Example: mystruct.cs