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

Similar documents
Industrial Programming

C# Types. Industrial Programming. Value Types. Signed and Unsigned. Lecture 3: C# Fundamentals

Industrial Programming

ITI Introduction to Computing II

Programs as Models. Procedural Paradigm. Class Methods. CS256 Computer Science I Kevin Sahr, PhD. Lecture 11: Objects

JAVA: A Primer. By: Amrita Rajagopal

ITI Introduction to Computing II

index.pdf January 21,

Objects and Classes. Amirishetty Anjan Kumar. November 27, Computer Science and Engineering Indian Institue of Technology Bombay

ITI Introduction to Computing II

ITI Introduction to Computing II

Java Object Oriented Design. CSC207 Fall 2014

PROGRAMMING IN C AND C++:

Object Oriented Programming

Derived and abstract data types. TDT4205 Lecture 15

Use the scantron sheet to enter the answer to questions (pages 1-6)

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1

Week 8: Operator overloading

Example: Fibonacci Numbers

CSEN401 Computer Programming Lab. Topics: Introduction and Motivation Recap: Objects and Classes

Java Classes & Primitive Types

An introduction to Java II

ITI Introduction to Computing II

Topic 7: Algebraic Data Types

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

Encapsulation. Mason Vail Boise State University Computer Science

Assignment 2 - Specifications and Modeling

Computer Science II (20073) Week 1: Review and Inheritance

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

Classes. Classes. Classes. Class Circle with methods. Class Circle with fields. Classes and Objects in Java. Introduce to classes and objects in Java.

Babaria Institute of Technology Computer Science and Engineering Department Practical List of Object Oriented Programming with C

Where do we stand on inheritance?

Chapter 1: Object-Oriented Programming Using C++

Programming, numerics and optimization

CS304 Object Oriented Programming Final Term

OBJECT ORİENTATİON ENCAPSULATİON

CSCI-1200 Computer Science II Fall 2006 Lecture 23 C++ Inheritance and Polymorphism

CS-202 Introduction to Object Oriented Programming

Software Design and Analysis for Engineers

C# Fundamentals. Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh

CSCI-1200 Data Structures Fall 2017 Lecture 25 C++ Inheritance and Polymorphism

C# Programming for Developers Course Labs Contents

C++ Quick Guide. Advertisements

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

The return Statement

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

Chapter 6 Introduction to Defining Classes

Unit Title: Objects in Visual Basic.NET. Software Development Unit 4. Objects in Visual Basic.NET

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

7. C++ Class and Object

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

Overview. ITI Introduction to Computing II. Interface 1. Problem 1. Problem 1: Array sorting. Problem 1: Array sorting. Problem 1: Array sorting

Operator overloading

Lecture 06: Classes and Objects

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

Object-Oriented Programming Concepts

Principles of Software Construction: Objects, Design, and Concurrency. Objects (continued) toad. Spring J Aldrich and W Scherlis

STUDENT LESSON A5 Designing and Using Classes

Inheritance and Polymorphism

Polymorphism Part 1 1

Java Classes & Primitive Types

Recursion 1. Recursion is the process of defining something in terms of itself.

CH. 2 OBJECT-ORIENTED PROGRAMMING

Inheritance and Interfaces

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

2. The object-oriented paradigm!

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Instantiation of Template class

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

Class API. Class API. Constructors. CS200: Computer Science I. Module 19 More Objects

COS226 - Spring 2018 Class Meeting # 13 March 26, 2018 Inheritance & Polymorphism

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

CS 170, Section /3/2009 CS170, Section 000, Fall

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

COURSE 2 DESIGN PATTERNS

Object Oriented Software Development CIS Today: Object Oriented Analysis

EEE-425 Programming Languages (2013) 1

CSE115 Introduction to Computer Science I Coding Exercise #7 Retrospective Fall 2017


Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

What is an algorithm?

M255 Object Oriented Programming with Java

8359 Object-oriented Programming with Java, Part 2. Stephen Pipes IBM Hursley Park Labs, United Kingdom

Object-oriented basics. Object Class vs object Inheritance Overloading Interface

Lecture 7 Objects and Classes

Inheritance and Polymorphism

CS250 Intro to CS II. Spring CS250 - Intro to CS II 1

1B1b. Classes in Java Part III. Review. Static. Static (2) Example. Static (3) 1B1b Lecture Slides. Copyright 2004, Graham Roberts 1

G Programming Languages - Fall 2012

Creating and Using Objects

Object Oriented Programming (II)

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

Transcription:

What is an Object Industrial Programming Lecture 4: C# Objects & Classes Central to the object-oriented programming paradigm is the notion of an object. Objects are the nouns a person called John Objects have characteristics (fields, attributes or properties) John has black hair and is 20 years old Objects can perform actions (methods or functions) John can tell me the sum of two numbers Industrial Programming 1 Industrial Programming 2 What is a Class What is a Class (cont'd) Before we create an object, we must describe it: What characteristics it has (attributes/fields). What actions it can perform (methods/functions). The class is the blueprint / template / plan / recipe / description for the object. Here we describe the fields & methods for all objects of this type. An object is an instance of a class. Creating an object is often called instantiation. For example, we can define a class person with attributes name, age etc and then instantiate it to a name John Industrial Programming 3 We can create many objects from one class. may spend a lot of time creating the class initially, but creating many objects from the class is easy! Re-use! for example, we can have lots of buttons that all have the same attributes and methods available. BUT all objects created from one class are NOT identical. Same name & data types for the fields, but different field values (different state). Different button names, text, size etc. The values of these fields define the state of an object. Industrial Programming 4

x y z These shapes have common attributes. We could define a Rectangle class. Attributes: Name: Data Type: Each object has the same attribute names & data types, but different attribute values, i.e. x) Class name Attributes Methods Class Rectangle fillcolour height width Object (Instance of a Class) (Rectangle) Red 1cm 5cm y) z) Industrial Programming 5 Shows state. No need to indicate methods as they exist for a whole class Industrial Programming 6 Bank Account Declaring & Creating Objects Attribute: Account No. Surname Balance (in s) Methods: deposit withdraw Class CBankAccount accountno : int Surname: string Balance: double deposit(double) withdraw(double) Example Object (CBankAccount) 11111 Smith 101.00 Declare a name for an object of a specific type (class), e.g. BankAccount myaccount; Create (instantiate) an object of a specific type (class), e.g. myaccount = new BankAccount(11111, Smith ); Industrial Programming 7 Industrial Programming 8

Type/Class Events Has a Respond to Receives & Generates Has a State Object Has Methods/ Behaviour Has Properties/ attributes Affect using System; class Point public int x; public int y; Simple C# Class public Point(int x, int y) this.x = x; this.y = y; class Test public static void Main() Point point1 = new Point(5,10); Point point2 = new Point(20, 15); Console.WriteLine( Point1(0, 1), point1.x, point1.y); Console.WriteLine( Point2(0, 1), point2.x, point2.y); Industrial Programming 9 Industrial Programming 10 Example Explained A class named Point is defined. It has two integer members x and y. The class includes a constructor. A special method called to construct an instance of the class. It takes two integer parameters. Keyword this refers to the current instance. Industrial Programming 11 Class and Constructor Classes are declared by using the keyword class followed by the class name and a set of class members surrounded by curly braces. Every class has a constructor, which is called automatically any time an instance of a class is created. The purpose of constructors is to initialise class members when an instance of the class is created. Constructors do not have return values and always have the same name as the class. Industrial Programming 12

Constructors (cont'd) Default values of fields A default constructor, without parameters, is generated automatically. The user can define more constructors by overloading the default constructor, passing values to initialise fields. Object initialisers allow you to separate initialisation from the constructor method: BankAccount bonusacc = new BankAccount(1112, Smith ) balance = 20; ; Industrial Programming 13 Unless explicitly initialised in the constructor, fields will have these default values: Numeric (int, long...) 0 Bool Char Enum 0 Reference False '\0' null Industrial Programming 14 Anonymous Types Anonymous types reduce the coding overhead in creating a class. They are typically used for types that are used only once. They are useful in the context of LINQ when connecting to databases. Notation: var mycircle = new radius=3 ; Note that this variable is read-only. Industrial Programming 15 Example Explained (cont'd) Another class named Test is defined. It contains a static main function where program execution starts. In the main function, two Point objects (instances) are created (using new). The x and y coordinates of the two points are printed out. The data fields are accessed directly (public fields), not a good idea. Why? Industrial Programming 16

Hiding Data Fields Hiding Data Fields (cont'd) using System; class Point private int x; private int y; public Point(int x, int y) this.x = x; this.y = y; public int GetX() return(x); public int GetY() return(y); class Test public static void Main() Point point1 = new Point(5,10); Point point2 = new Point(20, 15); Console.WriteLine( Point1(0, 1), point1.getx(), point1.gety()); Console.WriteLine( Point2(0, 1), point2.getx(), point2.gety()); Access modifier private is used to hide data fields. Member functions are used to access the data fields. Member functions GetX() and GetY() take no input parameters and return an integer (the coordinate value). Industrial Programming 17 Industrial Programming 18 Access Modifiers public: no access restrictions private: only methods of the same class can access the field protected: only methods in the same class and in classes derived from it can access the field internal: accessible to methods of any class in this class' assembly (collection of files, wrapped up in a executable or library) Instance and Static Members Fields and methods can be instance or static members of the class. Each object has its own copy of an instance field. All fields so far have been instance fields. A static field exists just once for a class and is shared by all objects of that class. This is useful for counting the number of objects of a class. An example of a static field in the Points class: public static int noofpoints = 0; Industrial Programming 19 Industrial Programming 20

Static Methods The same distinction between instance and static members exists for methods. An instance method is always applied to an object and can access the object's fields via the this variable. E.g. point1.getx(); A static method is associated to class rather than an object and takes all arguments via its parameters. E.g. Console.WriteLine( Hello world! ); Industrial Programming 21 C# Properties Properties are another way of hiding fields Properties look like attributes but behave like methods: class Point private int x; private int y; public int PointX get return x; set this.x = value; // analogous for PointY Industrial Programming 22 C# Properties (cont'd) Every lookup for PointX will be translated into a call of the get function, e.g. Console.WriteLine("Point1(0, 1)", point1.pointx, point1.pointy); Every assignment to PointX will be translated into a call to the set function, e.g. point1.pointx += 10; As shorthand notation you can use automatic properties, matching the names to the fields public int PointX get ; set ; A private field PointX will be generated automatically by the compiler Industrial Programming 23 C# Methods The constructor, GetX() and GetY() are methods. A method can have four parts: Method name. Parameters list. Return type. Access modifier. Semantic information should be added in comments: What is the meaning of a parameter? What are the invariants of the method/class? Industrial Programming 25

Overloading C# allows you to define different versions of a method/function in class, and the compiler will automatically select the matching one based on the parameters supplied. Generally, you should consider overloading a method when you need several methods that take different parameters, but conceptually do the same thing. You should not use overloads when two methods really do different things. Example: Overloading public class AddingNumbers public int add(int a, int b) return a+b; public int add(int a, int b, int c) return a+b+c; Calling Overloaded Methods int i = add(2, 3); int j = add(2, 3, 4); Industrial Programming 26 Industrial Programming 27 Operator Overloading Using the operator keyword, it is possible to overload existing operators, public static Complex operator +(Complex a, Complex b) return new Complex(a.Real+b.Real, a.imag+b.imag); Inheritance A central concept in object-oriented programming. A class is derived from another class. This allows the programmer to build a class hierarchy. A main activity in program design is the design of a suitable class hierarchy. Useful for code reuse. Industrial Programming 28 Industrial Programming 29

Inheritance Example: Base Class using System; class Person private string fname; private string lname; private string address; Inheritance Example: Subclass using System; class Student: Person private string matricno; private string degree; public Person(string fname, string lname, string address) this.fname = fname; this.lname = lname; this.address = address; string GetfName()return fname; string GetlName()return lname; string GetAddress()return address; Industrial Programming 30 public Student(string fname, string lname, string address, string matricno, string degree): base(fname, lname, address) this.matricno = matricno; this.degree = degree; string GetMatricNo()return matricno; string GetDegree()return degree; Industrial Programming 31 Test Class Example Explained class Test public static void Main() Person p = new Person("John", "Smith", "Edinburgh"); Student s = new Student("Brian", "Hillman", "London", "99124678", "CS"); Console.WriteLine("Student matric no: 0 ", s.getmatricno()); Console.WriteLine("Student address: 0 ", s.getaddress()); Console.WriteLine("Person address: 0 ", p.getaddress()); Industrial Programming 32 Person is a base class. Student is a subclass of Person. It inherits all the fields and methods in Person and defines new ones. Its constructor uses this to distinguish member fields from method arguments. Its constructor uses the notation :base (fname,lname,address) to call the constructor of the base class with these arguments. Industrial Programming 33

Interfaces An interface is a contract. A class that implements an interface must implement all of its methods. Whereas a class can inherit from just one class, it can implement several interfaces. These interfaces characterise various roles the class can take. An Example of an Interface An interface IStorable, with methods for reading and writing data: interface IStorable void Read (); void Write(object obj); int Status get ; set ; Industrial Programming 34 Industrial Programming 35 An Example of an Interface Here is one possible implementation public class Document : IStorable public Document (string str) Console.WriteLine("Creating document with: 0", str); #region IStorable public void Read () Console.WriteLine("Executing document's read method for IStorable"); public void Write(object obj) Console.WriteLine("Executing document's write method for IStorable"); // property required by IStorable public int Status get; set ; #endregion Industrial Programming 36 3 Pillars of Object-oriented Programming Encapsulation: each class should be selfcontained to localise changes. Realised through public and private access modifiers. Specialisation: model relationships between classes. Realised through inheritance. Polymorphism: treat a collection of items as a group. Realised through methods at the right level in the class hierarchy. Industrial Programming 37

Exercises (a) Implement the bank account example as discussed in the lecture. (b) Complete the Points example and implement access to the x- and y-fields, using direct access, public methods, and (automatic) properties, respectively. Exercises (a) Use inheritance and overloading to define a method Area, that works on different shapes, namely circles, rectangles and squares. (b) Let the user decide how many of these objects to construct, with which parameters, calculate the overall and per-shape area and print it (c) Write a (polymorphic) function that takes an array of shapes and calculates the total area covered by all elements. Industrial Programming 39 Industrial Programming 40 Exercises (a) Modify the ReadLine exercise from the previous lecture to generate instances of classes containing an unsigned short, unsigned int and unsigned long field, respectively. (b) Implement basic arithmetic on complex numbers using operator overloading. (c) Implement the data structure of binary search trees with operations for inserting and finding an element. Industrial Programming 41