EEE-425 Programming Languages (2013) 1

Similar documents
EEE-425 Programming Languages (2013) 1

Basic Object-Oriented Concepts. 5-Oct-17

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

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Chapter 5 Object-Oriented Programming

Object Oriented Programming in C#

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

Chapter 6 Introduction to Defining Classes

Chapter 12. OOP: Creating Object-Oriented Programs The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

Unit3: Java in the large. Prepared by: Dr. Abdallah Mohamed, AOU-KW

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Duhok Polytechnic University Amedi Technical Institute/ IT Dept. Halkawt Rajab Hussain

Lecture 18 Tao Wang 1

JAVA: A Primer. By: Amrita Rajagopal

Data Structures (list, dictionary, tuples, sets, strings)

Java Fundamentals (II)

C++ Important Questions with Answers

CS304 Object Oriented Programming Final Term

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Chapter 9 Objects and Classes. Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.

Object Oriented Programming

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Abstract Data Types and Encapsulation Concepts

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

CH. 2 OBJECT-ORIENTED PROGRAMMING

CS313D: ADVANCED PROGRAMMING LANGUAGE

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

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

Getter and Setter Methods

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Chapter 10 Classes Continued. Fundamentals of Java

Introduction To C#.NET


Data Structures using OOP C++ Lecture 3

An Introduction to C++

Inheritance (Part 5) Odds and ends

Java: introduction to object-oriented features

CS313D: ADVANCED PROGRAMMING LANGUAGE

Object-Oriented Programming (Java)

G52CPP C++ Programming Lecture 13

Encapsulation. Mason Vail Boise State University Computer Science

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

Basic Principles of OO. Example: Ice/Water Dispenser. Systems Thinking. Interfaces: Describing Behavior. People's Roles wrt Systems

Starting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int,

Chapter 10 Introduction to Classes

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

Chapter 1 Getting Started

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Object-Oriented Programming

ENCAPSULATION AND POLYMORPHISM

Principles of Object Oriented Programming. Lecture 4

OBJECT ORIENTED PROGRAMMING USING C++

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

CONSTRUCTOR & Description. String() This initializes a newly created String object so that it represents an empty character sequence.

CS304 Object Oriented Programming

CS201 - Introduction to Programming Glossary By

Chapter 11. Abstract Data Types and Encapsulation Concepts 抽象数据类型 与封装结构. 孟小亮 Xiaoliang MENG, 答疑 ISBN

Chapter 11. Abstract Data Types and Encapsulation Concepts ISBN

Cpt S 122 Data Structures. Introduction to C++ Part II

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

Tokens, Expressions and Control Structures

Data Abstraction. Hwansoo Han

CS111: PROGRAMMING LANGUAGE II

Java Object Oriented Design. CSC207 Fall 2014

What are the characteristics of Object Oriented programming language?

A Formal Presentation On Writing Classes With Rules and Examples CSC 123 Fall 2018 Howard Rosenthal

Polymorphism Part 1 1

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

CS1004: Intro to CS in Java, Spring 2005

Abstraction in Software Development

Object-Oriented Programming

Implementing Subprograms

ECE 3574: Dynamic Polymorphism using Inheritance

CS111: PROGRAMMING LANGUAGE II

Lecture #1. Introduction to Classes and Objects

IT 374 C# and Applications/ IT695 C# Data Structures

Chapter 02 Building Multitier Programs with Classes

Chapter 4 Defining Classes I

A A B U n i v e r s i t y

Objects and Classes. Lecture 10 of TDA 540 (Objektorienterad Programmering) Chalmers University of Technology Gothenburg University Fall 2017

Fundamental Concepts and Definitions

Inheritance, Polymorphism, and Interfaces

Short Notes of CS201

Topics. Topics (Continued) 7.1 Abstract Data Types. Abstraction and Data Types. 7.2 Object-Oriented Programming

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

OBJECTS AND CLASSES CHAPTER. Final Draft 10/30/2011. Slides by Donald W. Smith TechNeTrain.com

Interview Questions of C++

COEN244: Class & function templates

CS-202 Introduction to Object Oriented Programming

Introduction to Inheritance

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Chapter 4: Writing Classes

Lecture 5: Inheritance


Transcription:

2 Learn about class concepts How to create a class from which objects can be instantiated Learn about instance variables and methods How to declare objects How to organize your classes Learn about public fields and private methods Learn about the this and base references How to write constructor methods How to pass parameters to constructors How to overload constructors How to write destructor methods 3 4 There are two distinct types of classes created in C#: Classes that contain a Main() method Classes from which you instantiate objects Everything is considered an object in the objectoriented approach Object-oriented programmers recognize is-a relationships An object contains both data and methods that manipulate that data The data represent the state of the object Data can also describe the relationships between this object and other objects Example: A CheckingAccount might have A balance (the internal state of the account) An owner (some object representing a person) 5 6 EEE-425 Programming Languages (2013) 1

You could (in a game, for example) create an object representing a rabbit It would have data: How hungry it is How frightened it is Where it is And methods: eat, hide, run, dig Every object belongs to (is an instance of) a class An object may have fields, or variables The class describes those fields An object may have methods The class describes those methods A class is like a template, or cookie cutter You use the class s constructor to make objects 7 8 An Abstract Data Type (ADT) bundles together: some data, representing an object or "thing" the operations on that data The operations defined by the ADT are the only operations permitted on its data Classes enforce this bundling together If all data values are private, a class can also enforce the rule that its defined operations are the only ones permitted on the data 9 10 instance = object field = instance variable method = function sending a message to an object = calling a function These are all approximately true Classes are arranged in a treelike structure called a hierarchy The class at the root is named Object Every class, except Object, has a superclass A class may have several ancestors, up to Object When you define a class, you specify its superclass If you don t specify a superclass, Object is assumed Every class may have one or more subclasses 11 12 EEE-425 Programming Languages (2013) 2

Container Panel ScrollPane Window Dialog Frame A class header or class definition contains three parts: An optional access modifier The keyword class Any legal identifier you choose for the name of your class FileDialog A FileDialog is a Dialog is a Window is a Container 13 14 Private and protected classes have limited uses When you declare a class using a namespace, you can only declare it to be public or internal Class access is internal by default Instance variables are created using the same syntax used to declare other variables The allowable field modifiers are new, public, protected, internal, private, static, readonly, and volatile 15 16 Identifying a field as private means that no other class can access the field s value, and only methods of the same class will be allowed to set, get, or otherwise use the field Using private fields within classes is an example of information hiding Although most fields are private, most class methods are public Public : Public is the most commonly used access specifier in C#. It can be access from anywhere, that means there is no restriction on accessibility. The scope of the accessibility is inside class as well as outside. The type or member can be accessed by any other code in the same assembly or another assembly that references it. Protected : The scope of accessibility is limited within the class or struct and the class derived from this class. the members of Protected access specifier can be accessed Internal :The internal access modifiers can access within the program that contain its declarations and also access within the same assembly level but not from another assembly. Protected Internal : Protected internal is the same access levels of both protected and internal. It can access anywhere in the same assembly and in the same class also the classes inherited from the same class. 17 18 EEE-425 Programming Languages (2013) 3

In the following code, the variable idnumber is private, yet remains accessible to outside classes through the GetId() method Methods used with object instantiations are called instance methods It creates a method that is a counterpart to the GetID() method, called SetId() The SetId() method does not return any value, rather, it is used to assign a value in the class 19 20 Declaring a class does not create any actual objects A two step process creates an object that is an instance of a class: Supply a type and an identifier Allocate computer memory for the object Declaring an object notifies the compiler of the identifier and the type, but it does not allocate memory To allocate the needed memory for an object, use the new operator For example: Employee myassistant = new Employee(); The value being assigned to myassistant is a memory address at which it will be located Any class created can be referred to as a reference type, while the predefined types are called value types The method called after the new keyword is called the constructor method 21 22 All code executes in a method Constructors, destructors and operators are special types of methods Properties and indexers are implemented with get/set methods Methods have argument lists Methods contain statements Methods can return a value When you create an application that uses multiple class definitions, the class definitions can be stored in either a single file or each can be placed in its own file Storing all class definitions in one file shortens development time and simplifies the compilation process Using separate files for each class definition provides a more organized and manageable technique, and it allows for easier reusability 24 EEE-425 Programming Languages (2013) 4

Most classes you create will have multiple methods and fields, which can become difficult to track in large programs It is a good idea to arrange fields and methods in a logical order: Alphabetically By Sets and Gets Pairing of Sets and Gets In addition to organizing fields and methods, comments should also be used 25 26 The private fields/public method arrangement ensures that data will be used and changed only in ways provided in your methods Although it is easier to declare fields as public, doing so is considered poor object-oriented programming design Data should always be hidden when possible and access should be controlled by well-designed methods Poorly designed Desk class and program that instantiates a Desk 27 28 Occasionally, there are instances where a data field should be declared as public A data field may be declared public if all objects of a class contain the same value for that data field The example declared a public const field A named constant within a class is always static The Carpet class 29 30 EEE-425 Programming Languages (2013) 5

When instances of a class are created, the resulting objects require separate memory locations in the computer In the following code, each object of Book would at least require separate memory locations for title, numpages, and Price Unlike the class fields that are unique to each instance, the methods of the class are shared Although the methods are shared, there must be a difference between two method calls (from different objects), because each returns a different value (based on their unique fields) When a method is called, you automatically pass a reference to the memory of the object into the method The implicitly passed reference is the this reference 31 32 Book class methods explicitly using the this reference Book class method that requires explicit this reference 33 34 Classes support information hiding Data members of a class can be declared as private Hides implementation details of the class Create accessor methods to access data Typically get () and set (), which are public Getters and setters Other classes access data via get() and set() method So long as the interface to get and set stay the same, the class can change how it represents its data Information hiding permits implementations to change without affecting using classes http://www.c-sharpcorner.com/uploadfile/891f80/this-keyword-in-c-sharp/ 35 EEE-425 Programming Languages (2013) 6

Provide procedural access to data Like accessors But have syntax similar to direct variable access foo.x instead of foo.getx(); Minor feature, but provides substantial improvement in readability and fluidity of programming Travis thumbs his nose at private property www.flickr.com/photos/sillygwailo/492070136/ [access-modifiers] return-type property-name get sequence of statements ending in a return (or throw) get accessor set sequence of statements set accessor Get accessor returns value of same type as return type Set accessors have implicit parameter named value Use to set internal data representation Properties can be public, private, protected Public: any class can access, private: only that class, protected: that class and children By convention, property names have initial capital ( X to access x ) using System; class Example int _number; public int Number get return this._number; set this._number = value; static void Main(string[] args) Example example = new Example(); example.number = 5; // set Console.WriteLine(example.Number); // get 39 class access // String Variable declared as private private static string name; public void print() Console.WriteLine("\nMy name is " + name); public string Name //Creating Name property get //get method for returning value return name; set // set method for storing value in name field. name = value; static void Main(string[] args) access ac = new access(); Console.Write("Enter your name:\t"); // Accepting value via Name property ac.name = Console.ReadLine(); ac.print(); Console.ReadLine(); public Example() // Set the private property. this.isfound = true; bool found; public bool IsFound get return this.found; private set// Can only be called in this class. this.found = value; using System; class Example static int count; public static int Count get // Side effect of this property. count++; return count; static void Main() Example example = new Example(); Console.WriteLine(example.IsFound); 41 static void Main() Console.WriteLine(Example.Count); Console.WriteLine(Example.Count); Console.WriteLine(Example.Count); 42 EEE-425 Programming Languages (2013) 7

using System; class Example public Example() // Use private setter in the constructor. this.id = new Random().Next(); public int Id get; private set; static void Main() Example example = new Example(); Console.WriteLine(example.Id); A constructor method is a method that establishes an object Constructors have the following characteristics There is NO return type. NOT even void The method name is the same name as the class Constructors can be overloaded In order to put the object into a usable state, its instance variables should be initialized to usable values This could be accomplished by calling the various set methods This is not always possible because it is not required that all instance variables have set methods. 43 44 Constructors - Example using System; class test int size; public test(int mysize) size = mysize; public void writeresult() Console.WriteLine(size); static void Main() test Mytest1 = new test(10); test Mytest2 = new test(20); Mytest1.writeresult(); Mytest2.writeresult(); You can create a constructor that sets the same value for all objects instantiated. The program can eventually call the method of the object to set the value. However, this might not always be the most efficient technique. 46 C# automatically provides a default constructor However if you create your own constructor, the automatically provided default constructor is not available C# constructor methods, like other methods, can be overloaded In this code, the constructor receives an argument and initializes the object with the appropriate information 47 48 EEE-425 Programming Languages (2013) 8

using System; public static void Main(string[] args) class BankAccount BankAccount a = new BankAccount(); private int cust_id; // Invokes Default Constructor private string cust_name; BankAccount b = new BankAccount(102, "Ben", 5000); private int bal; // Invokes Parameterized Constructor public BankAccount() BankAccount c = new BankAccount(b); // Invokes Copy Constructor cust_id = 1000; a.showdata(); cust_name = "Not Yet Specified"; b.showdata(); bal = 0; c.showdata(); public BankAccount(int cust_id, string cust_name, int bal) this.cust_id = cust_id; this.cust_name = cust_name; this.bal = bal; public BankAccount(BankAccount obj) cust_id = obj.cust_id; cust_name = obj.cust_name; bal = obj.bal; public void ShowData() Console.WriteLine("cust id = 0, customer name = 1, Bank Balance = 2", cust_id, cust_name, bal); 49 A destructor method contains the actions you require when an instance of a class is destroyed To explicitly declare a destructor method, use an identifier that consists of a tilde(~) followed by the class name Destructors cannot receive parameters and therefore cannot be overloaded A class can have at most one destructor 50 Destructor methods are automatically called when an object goes out of scope You cannot explicitly call a destructor The last object created is the first object destroyed Employee class with destructor method 51 52 using System; //The example II The base keyword can be used to access class members that are hidden by similarly named members of the current class public class Shape private int x, y; public override string ToString() return "x=" + x + ",y=" + y; internal class Circle : Shape private int r; public override string ToString() return base.tostring() + ",r=" + r; using System; //The example I class BaseClass public string Field1 = "In the base class"; class DerivedClass : BaseClass new public string Field1 = "In the derived class"; public void Display() Console.WriteLine("0", Field1); // Access the derived class. Console.WriteLine("0", base.field1); // Access the base class. static void Main() DerivedClass oc = new DerivedClass(); oc.display(); public class Owner protected string ID = "2015513999"; protected string name = "Abdulcambaz Uzunkavakaltindayataruyumazoglu"; public virtual void Info() Console.WriteLine("Name : 0", name); Console.WriteLine("ID : 0", ID); class Student : Owner public string department = "EEM"; public override void Info() base.info(); // Calling the base class GetInfo method: Console.WriteLine("Student Department: 0", department); class TestClass public static void Main() Student E = new Student(); E.Info(); Console.ReadLine(); 54 EEE-425 Programming Languages (2013) 9

The is operator is used to dynamically test if the run-time type of an object is compatible with a given type private static void DoSomething(object o) if (o is Car) ((Car)o).Drive(); The as operator tries to convert a variable to a specified type; if no such conversion is possible the result is null More efficient than using is operator Can test and convert in one operation private static void DoSomething(object o) Car c = o as Car; if (c!= null) c.drive(); Components of a method Class methods Parameters Predefined methods Value and nonvalue-returning methods When you write programs in C#, you create two distinct type of classes When you create a class, you create a class header and a class body You declare the attributes and instance variables for a class within the curly braces using the same syntax you use to declare other variables Declaring a class does not create any actual objects After an object has been instantiated, its public methods can be accessed using the object s identifier, a dot, and a method call 57 58 When you create a class that describes objects you will instantiate, and another class that instantiates those objects, you physically can contain both classes within the same file or place each class in its own file Although there is no requirement to do so, most programmers place data fields in some logical order at the beginning of a class Most programmers make class data fields private and class methods public When you create an object, you provide storage for each of the object s instance variables, but not for each instance method A constructor method establishes an object Like any other C# methods, constructors can be overloaded A destructor method contains the actions you require when an instance of a class is destroyed 59 60 EEE-425 Programming Languages (2013) 10

homepage.divms.uiowa.edu Questions? Prof. Roger Crawfis http://www.cse.ohiostate.edu/~crawfis/cse459_csharp/index.html Programming C#, 4th Edition - Jesse Liberty Chapt. 4 Pls listen the podcast about the chapter 4 (Roger Crawfis) These slides are changed and modified 62 Write a game program that Create a class Takes a number from user, Compares this number with generated random value between two given positive numbers User tries maximum3 times then if user knows says «You Win» OR You lost Write a program as a calculator with (*, /, +, -, % ) operators by using methods Check the values that are not 0(zero) or none numeric Write the result on screen with variables and operator 63 EEE-425 Programming Languages (2013) 11