EEE-425 Programming Languages (2013) 1

Similar documents
EEE-425 Programming Languages (2013) 1

Basic Object-Oriented Concepts. 5-Oct-17

Chapter 5 Object-Oriented Programming

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

Lecture 18 Tao Wang 1

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

Object Oriented Programming in C#

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

Chapter 6 Introduction to Defining Classes

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

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

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

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

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

Getter and Setter Methods

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

Chapter 10 Introduction to Classes

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

Object-Oriented Programming (Java)

CS304 Object Oriented Programming Final Term

Java Fundamentals (II)

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

Introduction To C#.NET

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

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

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


JAVA: A Primer. By: Amrita Rajagopal

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

Fundamental Concepts and Definitions

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

Chapter 10 Classes Continued. Fundamentals of Java

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

CH. 2 OBJECT-ORIENTED PROGRAMMING

Object Oriented Design

G52CPP C++ Programming Lecture 13

by Pearson Education, Inc. All Rights Reserved. 2

ENCAPSULATION AND POLYMORPHISM

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University

Encapsulation. Mason Vail Boise State University Computer Science

Data Structures using OOP C++ Lecture 3

Programming II (CS300)

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

C++ Important Questions with Answers

CS 247: Software Engineering Principles. ADT Design

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

Abstraction in Software Development

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

Java: introduction to object-oriented features

CS313D: ADVANCED PROGRAMMING LANGUAGE

Programming II (CS300)

Chapter 1 Getting Started

CS304 Object Oriented Programming

Object-Oriented Programming (OOP) Fundamental Principles of OOP

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE

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

Tokens, Expressions and Control Structures

An Introduction to C++

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

Polymorphism Part 1 1

Abstract Data Types and Encapsulation Concepts

Data Abstraction. Hwansoo Han

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

CHAPTER 7 OBJECTS AND CLASSES

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

Object Oriented Programming

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 12: Classes and Data Abstraction

COEN244: Class & function templates

ECE 3574: Dynamic Polymorphism using Inheritance

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

STUDENT LESSON A5 Designing and Using Classes

CS313D: ADVANCED PROGRAMMING LANGUAGE

Chapter 11. Abstract Data Types and Encapsulation Concepts ISBN

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

CS1004: Intro to CS in Java, Spring 2005

Inheritance CSC 123 Fall 2018 Howard Rosenthal

Principles of Object Oriented Programming. Lecture 4

Software Design and Analysis for Engineers

Inheritance, Polymorphism, and Interfaces

Chapter 4 Defining Classes I

Introduction to C# Applications

Declarations and Access Control SCJP tips

CMPT 117: Tutorial 1. Craig Thompson. 12 January 2009

Comments are almost like C++

Object-Oriented Programming

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

Object Oriented Design

Java Object Oriented Design. CSC207 Fall 2014

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

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

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

Chapter 4: Writing Classes

Programming in C# Inheritance and Polymorphism

CS111: PROGRAMMING LANGUAGE II

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

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

8.1 Inheritance. 8.1 Class Diagram for Words. 8.1 Words.java. 8.1 Book.java 1/24/14

CS111: PROGRAMMING LANGUAGE II

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 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 Although most fields are private, most class methods are public 17 18 EEE-425 Programming Languages (2013) 3

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 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 19 20 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 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 21 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 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 23 24 EEE-425 Programming Languages (2013) 4

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 In addition to organizing fields and methods, comments should also be used Data should always be hidden when possible and access should be controlled by well-designed methods 25 26 Poorly designed Desk class and program that instantiates a Desk The Carpet class 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 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 The example declared a public const field A named constant within a class is always static 29 30 EEE-425 Programming Languages (2013) 5

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 Book class methods explicitly using the this reference 31 32 Book class method that requires explicit this reference http://www.c-sharpcorner.com/uploadfile/891f80/this-keyword-in-c-sharp/ 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 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/ EEE-425 Programming Languages (2013) 6

[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 ) 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; class Program 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(); 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. class Program static void Main() DerivedClass oc = new DerivedClass(); oc.display(); namespace ConsoleApplication1 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(); 40 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(); EEE-425 Programming Languages (2013) 7

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. Constructors - Example public class BankAccount String ownersname; int accountnumber; float balance; public BankAccount() public BankAccount(int anaccountnumber) accountnumber = anaccountnumber; public BankAccount(int anaccountnumber, String aname) accountnumber = anaccountnumber; ownersname = aname; [...] 43 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. In this code, the constructor receives an argument and initializes the object with the appropriate information 45 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 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 47 48 EEE-425 Programming Languages (2013) 8

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 49 50 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 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 51 52 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 Components of a method Class methods Parameters Predefined methods Value and nonvalue-returning methods 53 54 EEE-425 Programming Languages (2013) 9

Properties Instance methods Constructors Mutators Accessors Types of parameters Questions? 55 homepage.divms.uiowa.edu 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 57 EEE-425 Programming Languages (2013) 10