Lecture 13 Writing Classes Richard Gesick.

Slides:



Advertisements
Similar presentations
Based on Java Software Development, 5th Ed. By Lewis &Loftus
Advertisements

Object-Oriented Programming. Agenda Classes & Objects Attributes Methods Objects in memory Visibility Properties (get & set) Constructors.
Inheritance Polymorphism Briana B. Morrison CSE 1302C Spring 2010.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Immutable Objects and Classes.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Class Modifiers So far we have seen many examples of such modifiers E.g. Public Abstract etc.
CSE 1301 Lecture 11 Object Oriented Programming Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
CSE 1301 Lecture 4 Using Classes Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
C# D1 CSC 298 Elements of C# code (part 2). C# D2 Writing a class (or a struct)  Similarly to Java or C++  Fields: to hold the class data  Methods:
Checking Equality of Reference Variables. Arrays and objects are both “reference” types n They are allocated a chunk of memory in the address space n.
CSE 114 Computer Science I Objects Lake Superior, Michigan.
CSE 1301 Lecture 5 Writing Classes Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Chapter 7 Object-Oriented Programming Part 2: User-Defined Classes.
Object Oriented Programming (OOP) Lecture No. 11.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
CSE 1301 Lecture 6 Writing Classes Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Copyright © 2002 W. A. Tucker1 Chapter 10 Lecture Notes Bill Tucker Austin Community College COSC 1315.
Object Oriented Programming. OOP  The fundamental idea behind object-oriented programming is:  The real world consists of objects. Computer programs.
CS 116 Lecture 1 John Korah Contains content provided by George Koutsogiannakis & Matt Bauer.
Attribute - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 12/24/2016.
Topics Instance variables, set and get methods Encapsulation
1 Data Structures CSCI 132, Spring 2014 Lecture 2 Classes and Abstract Data Types Read Ch Read Style Guide (see course webpage)
INTRODUCTION TO CLASSES & OBJECTS CREATING CLASSES USING C#
1 More About Derived Classes and Inheritance Chapter 9.
Creating Your Own Classes
Classes (Part 1) Lecture 3
Classes and OOP.
Chapter 3: Using Methods, Classes, and Objects
Lecture 14 Writing Classes part 2 Richard Gesick.
Object-Oriented Programming Using C++
Week 8 Lecture -3 Inheritance and Polymorphism
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Lecture 9 Concepts of Programming Languages
CS Week 13 Jim Williams, PhD.
Lecture 4 Using Classes Richard Gesick.
More Object Oriented Programming
CSC240 Computer Science III
Object Based Programming
Classes and Objects: Encapsulation
Lecture 11 C Parameters Richard Gesick.
C# Object Oriented Programming Concepts
Classes and Objects Encapsulation
Chapter 4: Writing classes
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Outline Writing Classes Copyright © 2012 Pearson Education, Inc.
Implementing Non-Static Features
Advanced Programming Behnam Hatami Fall 2017.
© A+ Computer Science - OOP Pieces © A+ Computer Science -
Outline Anatomy of a Class Encapsulation Anatomy of a Method
COP 3330 Object-oriented Programming in C++
Fundaments of Game Design
Abstract Classes and Interfaces
Object-Oriented Programming and class Design
CIS 199 Final Review.
Class.
Object-Oriented Programming
Object-Oriented Programming and class Design
OO Programming Concepts
Object-Oriented Design AND CLASS PROPERTIES
Chapter 11 Inheritance and Encapsulation and Polymorphism
CMSC 202 Encapsulation Version 9/10.
Object-Oriented Programming and class Design
Object-Oriented Design AND CLASS PROPERTIES
Chapter 7 Objects and Classes
CSG2H3 Object Oriented Programming
Lecture 9 Concepts of Programming Languages
Chengyu Sun California State University, Los Angeles
Object-Oriented Design AND CLASS PROPERTIES
Presentation transcript:

Lecture 13 Writing Classes Richard Gesick

Topics Adding a Class to a Project Defining a Class Using a Class Attributes Methods Using a Class Visibility Instance Variables Properties

Multiple Classes in a Project adding classes to our project Keep them all in one file (~bad choice) One class per file (better choice)

Why User-Defined Classes? Primitive data types (int, double, char, .. ) are great … … but in the real world, we deal with more complex objects: products, Web sites, flight records, employees, students, .. Object-oriented programming enables us to manipulate real-world objects.

User-Defined Classes Combine data and the methods that operate on the data Advantages: Class is responsible for the validity of the data. Implementation details can be hidden. Class can be reused. Client of a class A program that instantiates objects and calls methods of the class

Classes A class can contain data declarations and method declarations int size, weight; char category; Data declarations Method declarations

Important Terminology Fields instance variables: data for each object class data: static data that all objects share Members fields and methods Access Modifier determines access rights for the class and its members defines where the class and its members can be used

Using the Class Before we define the Die class, let’s use it Remember that OOP allows us to ignore the “guts” and just presume it works There are 3+ categories of people involved The writer of the class (knows what the “guts” are) The user of the class, writing the main program (knows his code, but doesn’t know the class “guts”) The user of the program – sees the interface, doesn’t see program code at all

The “User” of a Class Recall we don’t want to have to expose the “guts” But we do need to tell a user of our class what it can do and what they have access to Define the API of the class

The Die Class API Die() Default constructor, sets sides to 6 Die(int s) Overloaded constructor, sets sides to s int roll() Returns a value from 1 to sides int Sides Property for sides with get and set string ToString() The overridden ToString method

Die UML Die -sides: int -rand:Random +Die(): +Die(int): +roll():int +ToString():string

using System; //gesick namespace L13_DiceClassDemo { class Program static void Main(string[] args) Die d = new Die(); Die d2 = new Die(); int num = 0; int num2 = 0; for (int i = 1; i <= 5; i++) num = d.Roll(); Console.WriteLine); num2 = d2.Roll(); Console.WriteLine(("d1 " + num +“ d2 " + num2); }

d2.Sides = 50; Console.WriteLine(d2); for (int i = 1; i <= 5; i++) { num = d.Roll(); num2 = d2.Roll(); Console.WriteLine("d1 " + num + "\td2 "+ num2 +"\tdice 2 sides = "+ d2.Sides); d2.Sides += 10; } Console.WriteLine(d2.ToString());

The output d1 3 d2 1 d1 2 d2 5 d1 2 d2 6 d1 6 d2 3 d1 1 d2 3 class die, number of sides is 50 d1 5 d2 26 dice 2 sides = 50 d1 1 d2 28 dice 2 sides = 60 d1 3 d2 50 dice 2 sides = 70 d1 3 d2 10 dice 2 sides = 80 d1 4 d2 17 dice 2 sides = 90 class die, number of sides is 100

The Die At this point, what do you know about Die from the code? You can “Roll()” it It has a number of sides You can make 2 different dice It has a ToString method You can change the number of sides Now let’s look at the guts…

Die Class with a static variable namespace L13_DiceClassDemo { /// <summary> /// uses a random number generator to simulate rolls on a die, values 1 to sides /// </summary> public class Die private static Random r; private int sides; /// default, creates a 6 sided die public Die() sides = 6; r = new Random(); }

Die Class (cont) /// <summary> /// overloaded, creates a s sided die /// </summary> /// <param name="s">the number of sides for the die</param> public Die(int s) { sides = s; r = new Random(); } /// returns a random value, 1 to sides /// <returns>the generated random number</returns> public int Roll() return r.Next(sides) + 1;

Die Class (cont) /// <summary> /// sides property with get and set /// </summary> public int Sides { get { return sides; } set { sides = value; } } /// returns the class name and number of sides of the die object /// <returns></returns> public override string ToString() return "class die, number of sides is " + sides;

Visibility OO motivation: protection/security We need a way of selectively “publishing” parts of a class and “hiding” other parts of the class Public & private

public vs. private Instance variables are usually declared to be private Methods that will be called by the client of the class are usually declared to be public Methods that will be called only by other methods of the class are usually declared to be private APIs of methods are published (made known) so that clients will know how to instantiate objects and call the methods of the class

Visibility Example Method are typically public class BMW_Z4 { private int ModelYear; public string LicensePlate; private bool TopUp; public void Drive() { Console.WriteLine("Roadin’ and Rockin’"); } public void OpenTop() TopUp = false; Note the visibility (attributes will usually be private) Method are typically public

Object Method & Attribute Visibility BMW_Z4 myCar; myCar = new BMW_Z4(); myCar.LicensePlate = "BMR4ME"; myCar.ModelYear = 2004; myCar.Drive(); myCar.OpenTop(); Illegal b/c private

Interacting with Objects Keep private/public visibility as needed

Visibility

Defining Instance Variables Syntax: accessModifier dataType identifierList; dataType can be primitive date type or a class type identifierList can contain: one or more variable names of the same data type multiple variable names separated by commas initial values Optionally, instance variables can be declared as const

Examples of Instance Variable Definitions private string name = ""; private const int PERFECT_SCORE = 100, PASSING_SCORE = 60; private int startX, startY, width, height;

The Auto Class class Auto { private string model; private int milesDriven; private double gallonsOfGas; }

Properties Combines field/attribute with method Standard: Make attributes private Lower-case first letter of attribute Make properties public Upper-case first letter of properties Define “get” and “set” for each property (selectively)

Properties Example class BMW_Z4 { private string licensePlate; private int modelYear; private string licensePlate; private bool topUp; public int ModelYear { get { return modelYear; } set { if (value >= 2003) modelYear = value; } } public string LicensePlate get { return licensePlate; } set { if (value.Length() == 6) licensePlate = value; } } ...

Auto Properties Now how would you write the properties for the Auto class? class Auto { private string model; private int milesDriven; private double gallonsOfGas; }