Topics. Classes. Classes CS 146. Classes and Objects Module Objectives. Classes and Objects Chapter Objectives

Similar documents
D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

Moving from CS 61A Scheme to CS 61B Java

Chapter 1 Java Program Design and Development

D06 PROGRAMMING with JAVA

Java Classes. GEEN163 Introduction to Computer Programming

CS 111 Classes I 1. Software Organization View to this point:

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Introduction to Object-Oriented Programming

Install Java Development Kit (JDK) 1.8

Java CPD (I) Frans Coenen Department of Computer Science

Chapter 13 - Inheritance

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

Example of a Java program

Unit Testing & JUnit

LAB4 Making Classes and Objects

AP Computer Science Java Subset

VB.NET - CLASSES & OBJECTS

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

More on Objects and Classes

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Glossary of Object Oriented Terms

UML Class Diagrams. Lesson Objectives

11 November

Java Application Developer Certificate Program Competencies

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

Object-Oriented Programming Lecture 2: Classes and Objects

Java Interview Questions and Answers

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Computer Programming I

Java Crash Course Part I

C++ INTERVIEW QUESTIONS

Basic Object-Oriented Programming in Java

Java Basics: Data Types, Variables, and Loops

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Many applications consist of one or more classes, each containing one or more methods. If you become part of a development team in industry, you may

History OOP languages Year Language 1967 Simula Smalltalk

CS 106 Introduction to Computer Science I

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game

Part 1 Foundations of object orientation

Object Oriented Software Design - I

Part I. Multiple Choice Questions (2 points each):

Contents. 9-1 Copyright (c) N. Afshartous

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

Object Oriented Software Design

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Understanding class definitions

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Inheritance, overloading and overriding

Lecture 5: Java Fundamentals III

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

An Introduction To UML Class Diagrams Classes

Object Oriented Software Design

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For

J a v a Quiz (Unit 3, Test 0 Practice)

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

Java (12 Weeks) Introduction to Java Programming Language

Introduction to Java. CS 3: Computer Programming in Java

AP Computer Science A - Syllabus Overview of AP Computer Science A Computer Facilities

CS170 Lab 11 Abstract Data Types & Objects

3D Animation of Java Program Execution for Teaching Object Oriented Concepts

Chapter 2 Introduction to Java programming

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

Introduction to programming

Description of Class Mutation Mutation Operators for Java

ICOM 4015: Advanced Programming

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

Algorithms, Flowcharts & Program Design. ComPro

Object Oriented Programming Design Basics CMSC 202

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Object-Oriented Programming in Java

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

Computer Programming I & II*

Classes and Objects. Agenda. Quiz 7/1/2008. The Background of the Object-Oriented Approach. Class. Object. Package and import

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Java Programming Fundamentals

Chapter 2 Elementary Programming

Fundamentals of Java Programming

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

13 Classes & Objects with Constructors/Destructors

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

CSC 221: Computer Programming I. Fall 2006

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Chapter 2: Elements of Java

AP Computer Science Static Methods, Strings, User Input

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Programming and Software Development CTAG Alignments

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Object Oriented Software Design II

Introduction to Java Lecture Notes. Ryan Dougherty

ECE 341 Coding Standard

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

ATM Case Study OBJECTIVES Pearson Education, Inc. All rights reserved Pearson Education, Inc. All rights reserved.

WRITING DATA TO A BINARY FILE

Transcription:

Introduction to Programming and Algorithms Module 3 CS 146 Sam Houston State University Dr. Tim McGuire Classes and Objects Module Objectives To understand: how classes are used as blueprints for objects the difference between a class and an object how attributes are implemented as fields how access specifiers control the access to fields and methods how to write a simple class and create instances of it in numerous programs methods that accept arguments methods that return a value the difference between accessor and mutator methods the concept of stale data 2 Classes and Objects Chapter Objectives To understand: how to identify the class name, attributes, methods, access specifiers, data types, and parameters in a UML diagram the concept of instance fields and instance methods what a constructor is how to write a constructor that accepts arguments what a default constructor is scope and how it relates to local variables, fields, and parameter variables data type ranking and know how Java performs widening conversions, and how to write statements using cast operators to manually perform conversions Topics Module 3 discusses the following main topics: Classes More about Passing Arguments Instance Fields and Methods Constructors A BankAccount Class Classes, Variables, and Scope Focus on Object Oriented Design 3 4 Classes Classes From Module 2, we learned that a reference variable contains the address of an object. String cityname = Charleston cityname Address to the object The object that contains the character string Charleston Charleston 5 The length() method of the String class returns and integer value that is equal to the length of the string. int stringlength = cityname.length(); The variable stringlength will contain 10 after this statement since the String Charleston has 10 characters. Primitive can not have methods that can be run whereas objects can. A class can be thought of as a blueprint that objects are created from. 6 1

Classes and Instances Classes and Instances Many objects can be created from a class. Each object is independent of the others. String person = Jenny ; String pet = Fido ; String favoritecolor = Blue ; person pet Address Address Jenny Fido favoritecolor Address Blue 7 8 Classes and Instances Each instance of the class String contains different data. The instances are all share the same design. Each instance has all of the attributes and methods that were defined in the String class. Classes are defined to represent a single concept or service. 9 Access Modifiers An access modifier is a Java keyword that indicates how a field or method can be accessed. There are three Java access modifiers: public private protected (covered later) 10 Access Modifiers public: This access modifier states that any other class can access the resource. private: This access modifier indicates that only data within this class can access the resource. These will be explained in greater detail later. Access Modifiers Classes that need to be used by other classes are typically made public. If there are more than one class in a file, only one may be public and it must match the file name. Class headers have a format: AccessModifier class ClassName Class Members 11 12 2

Encapsulation Designing a Class Classes should be as limited in scope as needed to accomplish the goal. Each class should contain all that is needed for it to operate. Enclosing the proper attributes and methods inside a single class is called encapsulation. Encapsulation ensures that the class is self-contained. 13 When designing a class, decisions about the following must be made. what data must be accounted for, what actions need to be performed, what data can be modified, what data needs to be accessible, and any rules as to how data should be modified. Class design typically is done with the aid of a Unified Modeling Language (UML) diagram. 14 UML Class Diagram Attributes A UML class diagram is a graphical tool that can aid in the design of a class. The diagram has three main sections. ClassName Attributes Methods UML diagrams are easily converted to Java class files. There will be more about UML diagrams a little later. The class name should concisely reflect what the class represents. 15 The data elements of a class defines the object to be instantiated from the class. The attributes must be specific to the class and define it completely. Example: A rectangle is defined by length width. The attributes are then accessed by methods within the class. 16 Data Hiding Another aspect of encapsulation is the concept of data hiding. Classes should not only be self-contained but they should be self-governing as well. Classes use the private access modifier on fields to hide them from other classes. Classes need methods to allow access and modification of the class data. Methods The class methods define what actions an instance of the class can perform Methods headers have a format: AccessModifier ReturnType MethodName(Parameters) //Method body. Methods that need to be used by other classes should be made public. 17 18 3

Methods The attributes of a class might need to be: changed, accessed, and calculated. The methods that change and access attributes are called Accessors and Mutators. Accessors and Mutators Because of the concept of data hiding, fields in a class are private. The methods that retrieve the data of fields are called accessors. The methods that modify the data of fields are called mutators. Each field that the programmer wishes to be viewed by other classes needs an accessor. Each field that the programmer wishes to be modified by other classes needs a mutator. 19 20 Accessors and Mutators For the rectangle example, the accessors and mutators are: setlength : Sets the value of the length field. public void setlength(double len) setwidth : Sets the value of the width field. public void setlength(double w) getlength : Returns the value of the length field. public double getlength() getwidth : Returns the value of the width field. public double getwidth() Other names for these methods are get methods and set methods. Stale Data Some data is the result of a calculation. Consider the area of a rectangle. length x width It would be impractical to use an area variable here. Data that requires the calculation of various factors has the potential to become stale. To avoid stale data, it is best to calculate the value of that data within a method rather than store it in a variable. 21 22 Stale Data Rather than use an area variable in a rectangle class: public double getarea() return length * width; This dynamically calculates the value of the rectangle s area when the method is called. Now, any change to the length or width variables will not leave the area of the rectangle stale. UML Data Type and Parameter Notation UML diagrams are language independent. UML diagrams use an independent notation to show return types, access modifiers, etc. Access modifiers are denoted as: + public - private 23 24 4

UML Data Type and Parameter Notation UML diagrams are language independent. UML diagrams use an independent notation to show return types, access modifiers, etc. Variable types are placed after the variable name, separated by a colon. UML Data Type and Parameter Notation UML diagrams are language independent. UML diagrams use an independent notation to show return types, access modifiers, etc. Method return types are placed after the method declaration name, separated by a colon. 25 26 UML Data Type and Parameter Notation UML diagrams are language independent. UML diagrams use an independent notation to show return types, access Method parameters are shown inside the parenthesis using the same notation as variables. modifiers, etc. 27 Converting the UML Diagram to Code Putting all of this information together, a Java class file can be built easily using the UML diagram. The UML diagram parts match the Java class file structure. class header Attributes Methods ClassName Attributes Methods 28 Converting the UML Diagram to Code The structure of the class can be compiled and tested without having bodies for the methods. Just be sure to put in dummy return values for methods that have a return type other than void. - length : double + setlength(len : double): void + getwidth() : double + getlength() : double + getarea() : double public class private double width; private double length; public void setwidth(double w) public void setlength(double len) public double getwidth() return 0.0; public double getlength() return 0.0; public double getarea() return 0.0; 29 Converting the UML Diagram to Code Once the class structure has been tested, the method bodies can be written and tested. - length : double + setlength(len : double: void + getwidth() : double + getlength() : double + getarea() : double public class private double width; private double length; public void setwidth(double w) width = w; public void setlength(double len) length = len; public double getwidth() return width; public double getlength() return length; public double getarea() return length * width; 30 5

Class Layout Conventions The layout of a source code file can vary by employer or instructor. Typically the layout is generally: Attributes are typically listed first Methods are typically listed second The main method is sometimes first, sometimes last. Accessors and mutators are typically grouped. There are tools that can help in formatting layout to specific standards. A Driver Program An application in Java is a collection of classes that interact. The class that starts the application must have a main method. This class can be used as a driver to test the capabilities of other classes. In the class example, notice that there was no main method. 31 32 public class Main public static void main(string [] args) r = new (); r.setwidth(10); r.setlength(10); System.out.println( Width = + r.getwidth()); System.out.println( Length = + r.getlength()); System.out.println( Area = + r.getarea()); This Main class is a Java application that uses the class. Another Example: LengthWidthDemo.java A Driver Program public class private double width; private double length; public void setwidth(double w) width = w; public void setlength(double len) length = len; public double getwidth() return width; public double getlength() return length; public double getarea() return length * width; 33 Multiple Arguments Methods can have multiple parameters. The format for a multiple parameter method is: AccessModifier ReturnType MethodName(ParamType ParamName, ParamType ParamName, etc) Parameters in methods are treated as local variables within the method. Example: MultipleArgs.java 34 Arguments Passed By Value Instance Fields and Methods In Java, all arguments to a method are passed by value. If the argument is a reference to an object, it is the reference that is passed to the method. If the argument is a primitive, a copy of the value is passed to the method. Fields and methods that are declared as previously shown are called instance fields and instance methods. Objects created from a class each have their own copy of instance fields. Instance methods are methods that are not declared with a special keyword, static. 35 36 6

Instance Fields and Methods Instance fields and instance methods require an object to be created in order to be used. Example: RoomAreas.java Note that each room represented in this example can have different dimensions. kitchen = new (); bedroom = new (); den = new (); Constructors Classes can have special methods called constructors. Constructors are used to perform operations at the time an object is created. Constructors typically initialize instance fields and perform other object initialization tasks. 37 38 Constructors Constructors have a few special properties that set them apart from normal methods. Constructors have the same name as the class. Constructors have no return type (not even void). Constructors may not return any values. Constructors are typically public. Example: ConstructorDemo.java Example: RoomConstructor.java 39 The Default Constructor If a default constructor is not defined, Java provides an empty one. It sets all of the class numeric fields to 0. It sets all of the class boolean fields to false. It sets all of the class reference variables, the default constructor sets them to the special value null. The default constructor is a constructor with no parameters. Default constructors are used to initialize an object in a default configuration. 40 Constructors in UML In UML, the most common way constructors are defined is: - length : double +(len:double, w:double): + setlength(len : double): void + getwidth() : double + getlength() : double + getarea() : double Notice there is no return type listed for constructors. The String Class Constructor One of the String class constructors accepts a String literal as an argument. This String literal is used to initialize a String object. For instance: String name = new String( Dr. Tim McGuire ); 41 42 7

The String Class Constructor The BankAccount Example This creates a new reference variable name that points to a String object that represents the name Dr. Tim McGuire Because they are used so often, Strings can be created with a shorthand: String name = Dr. Tim McGuire ; BankAccount - balance : double - interestrate : double - interest : double +BankAccount(startBalance:double, intrate :double): + deposit(amount : double) : void + withdrawl(amount : double: void + addinterest() : void + getbalance() : double + getinterest() : double Example Files: BankAccount.java AccountTest.java 43 44 Classes, Variables and Scope The list below shows the scope of a variable depending on where it is declared. Inside a method: Visible only within that method. Called a local variable. In a method parameter: Called a parameter variable. Same as a local variable Visible only within that method. Inside the class but not in a method: Visible to all methods of the class. Called an instance field. 45 Shadowing A parameter variable is, in effect, a local variable. Within a method, variable names must be unique. A method may have a local variable with the same name as an instance field. This is called shadowing. The local variable will hide the value of the instance field. Shadowing is discouraged and local variable names should not be the same as instance field names. 46 Object Oriented Design Finding Classes and Their Responsibilities Finding the classes Get written description of the problem domain Identify all nouns, each is a potential class Refine list to include only classes relevant to the problem Identify the responsibilities Things a class is responsible for knowing Things a class is responsible for doing Refine list to include only classes relevant to the problem Object Oriented Design Finding Classes and Their Responsibilities Identify the responsibilities Things a class is responsible for knowing Things a class is responsible for doing Refine list to include only classes relevant to the problem 47 48 8