Object Oriented Programming

Similar documents
Object Oriented Programming

classes, inheritance, interfaces, polymorphism simple and structured types, generics type safeness

Computing is about Data Processing (or "number crunching") Object Oriented Programming is about Cooperating Objects

C++ Important Questions with Answers

Chapter 5 Object-Oriented Programming

Java Object Oriented Design. CSC207 Fall 2014

Object-Oriented Programming

Introduce C# as Object Oriented programming language. Explain, tokens,

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Object-Oriented Design

CMSC 132: Object-Oriented Programming II

Object oriented programming. Encapsulation. Polymorphism. Inheritance OOP

Idioms and Design Patterns. Martin Skogevall IDE, Mälardalen University

Advanced Object-Oriented Programming. 11 Features. C# Programming: From Problem Analysis to Program Design. 4th Edition

02 Features of C#, Part 1. Jerry Nixon Microsoft Developer Evangelist Daren May President & Co-founder, Crank211

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class.

Topic 7: Algebraic Data Types

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Logistics. Final Exam on Friday at 3pm in CHEM 102

9 A Preview of.net 2.0

Objective Questions. BCA Part III Paper XIX (Java Programming) page 1 of 5

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes

Chapter 11. Abstract Data Types and Encapsulation Concepts ISBN

Inheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017

Industrial Programming

What is an Object. Industrial Programming. What is a Class (cont'd) What is a Class. Lecture 4: C# Objects & Classes

Design issues for objectoriented. languages. Objects-only "pure" language vs mixed. Are subclasses subtypes of the superclass?

Introduction to Programming Using Java (98-388)

What are the characteristics of Object Oriented programming language?

Introduction to C# Applications

Chapter 5: Procedural abstraction. Function procedures. Function procedures. Proper procedures and function procedures

Introduction to Programming Microsoft.NET Applications with Visual Studio 2008 (C#)

Absolute C++ Walter Savitch

CMSC 132: Object-Oriented Programming II

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

COMP 401 Spring 2013 Midterm 1

Programming in Visual Basic with Microsoft Visual Studio 2010

CSE Lecture 3: Objects 2 September Nate Nystrom University of Texas at Arlington

COP 3330 Final Exam Review

JAVA MOCK TEST JAVA MOCK TEST II

Programming Paradigms

administrivia today UML start design patterns Tuesday, September 28, 2010

Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7

Distributed Systems Recitation 1. Tamim Jabban

Programming II (CS300)

be used for more than one use case (for instance, for use cases Create User and Delete User, one can have one UserController, instead of two separate

PROGRAMMING IN VISUAL BASIC WITH MICROSOFT VISUAL STUDIO Course: 10550A; Duration: 5 Days; Instructor-led

Programming in C# with Microsoft Visual Studio 2010

Wrapping a complex C++ library for Eiffel. FINAL REPORT July 1 st, 2005

Learning C# 3.0. Jesse Liberty and Brian MacDonald O'REILLY. Beijing Cambridge Farnham Köln Sebastopol Taipei Tokyo

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Concepts of Programming Languages

Encapsulation. Mason Vail Boise State University Computer Science

Abstract Data Types and Encapsulation Concepts

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content

CS 231 Data Structures and Algorithms, Fall 2016

Chapter 11. Abstract Data Types and Encapsulation Concepts

A Primer on Design Patterns

Interview Questions I received in 2017 and 2018

EEE-425 Programming Languages (2013) 1

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

VIRTUAL FUNCTIONS Chapter 10

Inheritance and Polymorphism

Programming Exercise 14: Inheritance and Polymorphism

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Principles of Object Oriented Programming. Lecture 4

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

Introduction to Python

QUESTIONS FOR AVERAGE BLOOMERS

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Object-Oriented Programming in C# (VS 2015)

Object Oriented Programming. Solved MCQs - Part 2

Applied object oriented programming. 4 th lecture

Object Oriented Design

4.1 Introduction Programming preliminaries Constructors Destructors An example... 3

An Introduction to C++

How to be a C# ninja in 10 easy steps. Benjamin Day

Object-Oriented Concepts and Principles (Adapted from Dr. Osman Balci)

Design Patterns. Manuel Mastrofini. Systems Engineering and Web Services. University of Rome Tor Vergata June 2011

Problem Solving with C++

Polymorphism. Contents. Assignment to Derived Class Object. Assignment to Base Class Object

Chapter 11. Abstract Data Types and Encapsulation Concepts

G Programming Languages Spring 2010 Lecture 9. Robert Grimm, New York University

Patterns for polymorphic operations

Distributed Systems Recitation 1. Tamim Jabban

And Even More and More C++ Fundamentals of Computer Science

Object Oriented Paradigm

Software Construction

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

CS 1302 Chapter 9 (Review) Object & Classes

EEE-425 Programming Languages (2013) 1

Lecture 13: Object orientation. Object oriented programming. Introduction. Object oriented programming. OO and ADT:s. Introduction

Introduction to Object-Oriented Programming

+ Abstract Data Types

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Goals of design. satisfies problem requirements, usable error free, resistant to incorrect input. readable, not purposefully cryptic.

C#: framework overview and in-the-small features

Transcription:

Object Oriented Programming Objects self-contained working units encapsulate data and operations exist independantly of each other (functionally, they may depend) cooperate and communicate to perform a common task Classes are Object Types (abstract data types) are instantiated as Objects Inherit from other Classes form Type Hierarchies may redefine inherited behavior Polymorphically (c)schmiedecke 13 C#-3-OO 2

Structs do not inherit are not part of a type hierarchie do not offer polymorphism Why then structs? pragmatic reasons lightweight, less overhead, "cheaper" C# contains numerous "pragmatic" constructs (c)schmiedecke 13 C#-3-OO 3

class TypeHierarchy IEnumerable IEnumerable<T> ICollection ICollectio<T> IDictionary IList HashTable ArrayList LinkedList ILst<T> IDictionary<T> ArrayList<T> List<T> Dictionary<T> (c)schmiedecke 13 C#-3-OO 4

general and generic types are not directly compatible ArrayList a = new ArrayList<string>() will not compile! ArrayList list = new ArrayList<string>; // Compiler error! use superclasses as variable types to allow for compatibility! Find suitable types for the following situations: a variable to hold all sorts of generic Lists a parameter for passing Hashtables and general Lists a variable to hold both general and generic LinkedLists.. what else can these variables refer to? (c)schmiedecke 13 C#-3-OO 5

Interfaces serve as common types for varying implementations a programming "contract" Examples: allow a prototype implementation to be replaced by a production implementation without effect on code tell another programming team what I expect from them specify the contents of a library or have a common variable type for a variety of values. IRegister<T> mylist = new RegisterPrototype<T>(); // simply replace by SecureRegister later. (c)schmiedecke 13 C#-3-OO 6

Like in Java, Interfaces are fully abstract classes can extend further interfaces public or internal members automatically public abstract abstract methods abstract properties abstract indexers abstract events (later) public interface IGroupList : IEnumerable { } int Count { get; set } // abstract Property IClassList this[int index]; // abstract Indexer int Find(string name); // abstrac Method void remove(int index); void add(person p); (c)schmiedecke 13 C#-3-OO 7

Adapter: your travelagency software was using an old routing library you want to move on to a modern open-source version expose the requirements of your software as an interface write an Adapter class to implement the interface with the new library class Adapter class Adapter Trav elagency OldRouting Trav elagency IOldRouting + computeroute() : string[] + computeroute() : string[] RoutingAdadpter NewRouting + getruotings() : Route[] IOldRouting routing = new RoutingAdapter(); routing.computeroute(destinatiolist); (c)schmiedecke 13 C#-3-OO 8

Why didtravelagency not use an interface (IOldRouting) from the beginning? less dependant on the OldRoutingClass Dependency complicates change DIP: Program against interfaces to reduce dependency Always design interfaces for your classes! IList<Route> routelist = new LinkedList<Route>(); // very easy to change to ArrayList or another implementation // very easy to use a verbose debugging type instead during // implementation (c)schmiedecke 13 C#-3-OO 9

Proxy a client class refers to a "costly" object e.g. an image which needs downloading resources as long as the object is not really used, a mockup will do: Proxy when needed, the mockup will "secretly" get the object and delegate access. class Adapter class Adapter Photov iiewe Image Photov iiewe IImage + displayimage() : void + displayimage() : void ImageProxy + displayimage() : void Image + displaimage() : void class ImageProxy : IImage { void displayimage() { // download image when called Image img = loadimage(); img.displayimage(); } } (c)schmiedecke 13 C#-3-OO 10

These "Tricks" are well-known Design Patterns Every software professional must know them Good solutions to frequent problems Well-knowns structures improve code readability Original List by Gamma, Helm, Johnson and Vlissides Called Gang of Four Patterns or GoF Patterns (c)schmiedecke 13 C#-3-OO 11

Just like in Java A class can only inherit from ONE superclass but implement any number of Interfaces some Interfaces are empty "marker interfaces" test for type possible: mylist is ISerializable Interface IEnmuerable { Enumerator getenumerator(); } Interface IEnumerable<T> : IEnumerable { Enumerator<T> get Enumerator(); // addtional method } Interface ISerializable {} // empty marker interface class RandomEnumerator : IEnumerable<T>, ISerializable { } (c)schmiedecke 13 C#-3-OO 12

Interfaces are fully abstract Abstract classes are partly implemented specific methods open for implementation in subclasses Design Pattern: Template Method public abstract class Logger { string log; public void log(string logentry) { log += logentry } } public void closelog() { Save(); Clear(); } // template meth. abstract void Save(); public class FileLogger : Logger { public override void Save() { SendToFile(".\logfile.lg", log); } } (c)schmiedecke 13 C#-3-OO 13

static fields are not specific to instances the type manages them for all instances (family property) Class Windsor Chief: Queen E II Res: Buckingham P Home: Windsor C. static methods cannot access the instance use static fields, call static methods receive data via parameters create instance to call instance methods Charles William Elizabeth II static classes Kate contain only static members (c)schmiedecke 13 C#-3-OO 14

Utilities Global Constants General Computations and Conversions int age = Math.Min(myAge, yourage); string datestring = Convert.ToString(DateTime.Now); File.WriteAllText((@".\logfile.txt", logoutput, Encoding.UTF8); (c)schmiedecke 13 C#-3-OO 15

none, internal accessible within assembly (=project) OR public accessible from anywhere static contains only static members abstract only for subclassing, no instantiation OR sealed subclassing prohibited OR none find contradicting combinations! (c)schmiedecke 13 C#-3-OO 16

public accessible anywhere none, internal accessible within assembly (=project) protected accessible in subclasses private accessible within class (even other instances) static member belongs to class, not instance abstract not for fields virtual method: open for polymorphic overriding override method: polymorphic overriding const field: compiletime constant readonly field: immutable after initialization (c)schmiedecke 13 C#-3-OO 17

C# Fields Properties Indexer Events Delegates Methods JAVA Fields Methods (c)schmiedecke 13 C#-3-OO 18

variables, instance and static should be private, for internal use only naming convention: camelcase (start with small letter) extra modifiers for constants: public access reasonable const static const (global constant, naming convention capital, e.g. Math.PI) readonly class Person { private char internalstatus; // cryptic on purpose private static int currentwaitingtime; public const int id; } (c)schmiedecke 13 C#-3-OO 19

restricted dynamic typing standard in functional programming best known from scripting languages, like python, ruby, in C# mainly used in Lambda Expressions type of variable open until first assignation var MyVariant; // type yet unknown MyVariant = new DateTime(); // typed fixed to DateTime (c)schmiedecke 13 C#-3-OO 20

Programming best practice in all oo programs! private fields with get and set accessors shorthand declaration in C# readonly by omitting the setter class Person { private char internalstatus; // cryptic on purpose private static int currentwaitingtime; } private int id; public int Id { get { return id; } set { id = value; } } //automatic property: public int Id { get ; set } //with resticted access public int Id { get ; private set } (c)schmiedecke 13 C#-3-OO 21

void methods and functions like in Java naming convention PascalCase methods can take parameters and throw and handle exceptions (without declaring them) and from an puristic oo point of view, that's enough: an instance method reads or modifies "its" instance fields public class BankAccount { private decimal Balance; private decimal DebtLimit; private decimal Transit; public void Add(decimal amount) { } public void Transfer(decimal amount, BankAccount acc) { if (Balance + DebtLimit < amount) throw new BankingException(); Transit=amount; acc.add(amount); Transit=0; } } (c)schmiedecke 13 C#-3-OO 22

pragmatic programmers want: output parameters (if the return value is not enough) flexible parameter lists optional parameters named parameters static void SplitName(string Name, out string FirstNames, out string Surname) { string[] names = Name.Split(','); FirstNames = names[1]; Surname = names[0]; Name = ""; // useless } (c)schmiedecke 13 C#-3-OO 23

static void Main() { Person Annie = new Person("smith, annie"); Person Bruce = new Person("wild, bruce"); Exchange(Annie, Bruce) Console.WriteLine(Annie.Name, Bruce.Name); } static void Exchange (Person A, Person B) { Person C = A; A = B; B = C; } // no effect! { string c = A.Name; A.Name = B.Name; B.Name = c; } Annie Bruce smith, annie wild, bruce A B C Parameter passing by (reference) value copies to local variables (c)schmiedecke 13 C#-3-OO 24

ref turnes a paramter into a reference parameter out makes it an output parameter (no initialization required) ref and out required at declaration and call! static void SplitName(ref string Name, out string FirstNames, out string Surname) { string[] names = Name.Split(','); FirstNames = names[1]; Surname = names[0]; Name = ""; // clears origial entry } /// SplitName(ref Annie.Name, out Annie.Name, out Bruce.Name); (c)schmiedecke 13 C#-3-OO 25

list fixed parameters first, then flexibles params type[ ] name stands for a variable length list of "type" parameters static void Add(out int sum, params int[]vals) { sum = 0; foreach (int i in vals) sum += i; } // Add(out balance, 11,22,33,44,55,66,77,88,99); Add(out sum, sum, a,b,c); Add(out x) (c)schmiedecke 13 C#-3-OO 26

Standard in programming is position parameters name-value pairs in many other contexts, e.g. HTTP request allows for arbitrary order in calls method declaration unchanged static void PrintAddress (string street, int numer, int zip, string city) { } // PrintAddress("High Street", 24, 1234, "NewGardens"); PrintAddress("High Street", city: "NewGardens", number: 24, zip: 1234); (c)schmiedecke 13 C#-3-OO 27

assign default value in parameter declaration can be omitted at call often combination with named parameters more elegant solution: method overloading static void PrintAddress (string street, int number, int zip = 1234, string city = "NewGardens") { } // PrintAddress("High Street", 24) PrintAddress("Low Street", city: "OldGardens", number: 24); (c)schmiedecke 13 C#-3-OO 28

(c)schmiedecke 13 C#-3-OO 29

(c)schmiedecke 13 C#-3-OO 30