I NTRODUCTION TO PROGRAMMING Starting Out with Java: From Control Structures through Objects.

Slides:



Advertisements
Similar presentations
Lesson 13 Introduction to Classes CS1 Lesson Introduction to Classes1.
Advertisements

Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 9 Classes.
Chapter 6: A First Look at classes. Object-Oriented Programming  Object-oriented programming is centered on creating objects rather than procedures.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 11 Classes and Object- Oriented Programming.
Road Map Introduction to object oriented programming. Classes
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
1 Fall 2007ACS-1903 Chapter 6: Classes Classes and Objects Instance Fields and Methods Constructors Overloading of Methods and Constructors Scope of Instance.
Chapter 6: A First Look at Classes
Introduction to Classes, Objects, Methods and Attributes Lecture # 2.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
A First Look At Classes Chapter 6. Procedural Programming In procedural- programming all the program functionality is written in a few modules of code.
Starting Out With Java 5 (Control Structures to Objects) Chapter 6 By Tony Gaddis Copyright © 2005 Pearson Addison-Wesley. All rights reserved.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: From Control Structures through Objects Third Edition.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
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.
Starting Out with Java: From Control Structures through Objects.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
CS0007: Introduction to Computer Programming Classes: Documentation, Method Overloading, Scope, Packages, and “Finding the Classes”
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Addison Wesley is an imprint of © 2010 Pearson Addison-Wesley. All rights reserved. Chapter 12 Object-Oriented Programming Starting Out with Games & Graphics.
CIS 270—Application Development II Chapter 8—Classes and Objects: A Deeper Look.
CSci 162 Lecture 10 Martin van Bommel. Procedures vs Objects Procedural Programming –Centered on the procedures or actions that take place in a program.
© 2010 Pearson Addison-Wesley. All rights reserved. 6-1 Chapter Topics Chapter 6 discusses the following main topics: –Classes and Objects –Instance Fields.
Lecture 19: Introduction to Classes Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Introduction to Classes, Objects, Methods and Attributes Lecture # 5.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 3 A First Look at Classes and Objects.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
Starting Out With Java 5 Control Structures to Objects By Tony Gaddis Copyright © 2005, 2005 Pearson Addison-Wesley. All rights reserved. Chapter 6 Slide.
CS 106 Introduction to Computer Science I 03 / 22 / 2010 Instructor: Michael Eckmann.
In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The import statement and using prewritten.
Topics Instance variables, set and get methods Encapsulation
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Unified Modeling Language
CSCI 51 Introduction to Programming Dr. Joshua Stough February 26, 2009.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
CS16: UML’s Unified Modeling Language. UML Class Diagram A UML class diagram is a graphical tool that can aid in the design of a class. The diagram has.
Introduction to Constructors Lecture # 4. Copyright © 2011 Pearson Education, Inc. 3-2 Arguments Passed By Value In Java, all arguments to a method are.
Chapter 6 A First Look at Classes. 2 Contents 1. Classes and objects 2. Instance Fields and Methods 3. Constructors 4. Overloading Methods and Constructors.
Copyright © 2011 Pearson Education, Inc. Starting Out with Java: Early Objects Fourth Edition by Tony Gaddis Chapter 3: A First Look at Classes and Objects.
Chapter 6 A First Look at Classes. 2 Contents 1. Classes and objects 2. Instance Fields and Methods 3. Constructors 4. Overloading Methods and Constructors.
Procedural and Object-Oriented Programming
Topics Procedural and Object-Oriented Programming Classes
Chapter 3 Classes & Objects
Java Programming: Guided Learning with Early Objects
Java Primer 1: Types, Classes and Operators
A first Look at Classes.
Introduction to Classes
Chapter 6: A First Look at Classes
Introduction to Classes
Today’s topics UML Diagramming review of terms
Lecture 5- Classes, Objects and Methods
Object Oriented Programming in java
Lecture 8 Object Oriented Programming (OOP)
Chapter 6: A First Look at classes
Presentation transcript:

I NTRODUCTION TO PROGRAMMING Starting Out with Java: From Control Structures through Objects

GOAL The goal of this unit is to provide basic Java programming concepts and to get familiar with Java syntax. Departmental Goal 1: Application of the concepts Departmental Goal 2: Analyze and critically evaluate IDEA Objective 1: Learning to apply course material (to improve thinking, problem solving, and decisions) IDEA Objective 2: Learning to analyze and critically evaluate ideas, arguments, and points of view.

6-3 C HAPTER T OPICS Chapter 6 discusses the following main topics: Classes and Objects Instance Fields and Methods Constructors Overloading Methods and Constructors Scope of Instance Fields Packages and Import Statements

6-4 O BJECT -O RIENTED P ROGRAMMING Object-oriented programming is centered on creating objects rather than procedures. Objects are a melding of data and procedures that manipulate that data. Data in an object are known as fields. Procedures in an object are known as methods.

6-5 O BJECT -O RIENTED P ROGRAMMING Object Data (Fields) Methods That Operate on the Data

6-6 O BJECT -O RIENTED P ROGRAMMING Object-oriented programming combines data and behavior via encapsulation. Data hiding is the ability of an object to hide data from other objects in the program. Only an object’s methods should be able to directly manipulate its data. Other objects are allowed manipulate an object’s data via the object’s methods.

6-7 O BJECT -O RIENTED P ROGRAMMING Object Data (Fields) typically private to this object Methods That Operate on the Data Code Outside the Object

6-8 O BJECT -O RIENTED P ROGRAMMING D ATA H IDING Data hiding is important for several reasons. It protects the data from accidental corruption by outside objects. It hides the details of how an object works, so the programmer can concentrate on using it. It allows the maintainer of the object to have the ability to modify the internal functioning of the object without “breaking” someone else's code.

6-9 O BJECT -O RIENTED P ROGRAMMING C ODE R EUSABILITY A software object contains data and methods that represents a specific concept or service It is not a stand-alone program. Objects can be used by programs that need the object’s service. Reuse of code promotes the rapid development of larger software projects.

6-10 A N E VERYDAY E XAMPLE OF AN O BJECT —A N A LARM C LOCK Fields define the state that the alarm is currently in. The current second (a value in the range of 0-59) The current minute (a value in the range of 0-59) The current hour (a value in the range of 1-12) The time the alarm is set for (a valid hour and minute) Whether the alarm is on or off (“on” or “off”)

6-11 A N E VERYDAY E XAMPLE OF AN O BJECT —A N A LARM C LOCK Methods are used to change a field’s value Set time Set alarm time Turn alarm on Turn alarm off Increment the current second Increment the current minute Increment the current hour Sound alarm Public methods are accessed by users outside the object. Private methods are part of the object’s internal design.

6-12 C LASSES AND O BJECTS The programmer determines the fields and methods needed, and then creates a class. A class can specify the fields and methods that a particular type of object may have. A class is a “blueprint” that objects may be created from. A class is not an object, but it can be a description of an object. An object created from a class is called an instance of the class.

6-13 C LASSES AND O BJECTS Insect class The Insect class defines the fields and methods that will exist in all objects that are an instances of the Insect class. housefly object The housefly object is an instance of the Insect class. mosquito object The mosquito object is an instance of the Insect class.

6-14 O BJECTS VERSUS PRIMITIVE VARIABLES From chapter 2, we learned that a reference variable contains the address of an object. String cityName = "Charleston"; Charleston Address to the object cityName The object that contains the character string “Charleston”

6-15 O BJECTS VERSUS PRIMITIVE VARIABLES The length() method of the String class returns an integer value that is equal to the length of the string. int stringLength = cityName.length(); Class objects normally have methods that perform useful operations on their data. Primitive variables can only store data and have no methods.

6-16 C LASSES AND I NSTANCES Many objects can be created from a class. Each object is independent of the others. Each instance has all of the attributes and methods that were defined in the String class. String person = "Jenny "; String pet = "Fido"; “Jenny” Address person “Fido” Address pet

6-17 B UILDING A R ECTANGLE CLASS A Rectangle object will have the following fields: length. The length field will hold the rectangle’s length. width. The width field will hold the rectangle’s width.

6-18 B UILDING A R ECTANGLE CLASS The Rectangle class will also have the following methods: setLength. The setLength method will store a value in an object’s length field. setWidth. The setWidth method will store a value in an object’s width field. getLength. The getLength method will return the value in an object’s length field. getWidth. The getWidth method will return the value in an object’s width field. getArea. The getArea method will return the area of the rectangle, which is the result of the object’s length multiplied by its width.

6-19 UML D IAGRAM Unified Modeling Language (UML) provides a set of standard diagrams for graphically depicting object- oriented systems. Class name goes here Fields are listed here Methods are listed here

6-20 UML D IAGRAM FOR R ECTANGLE CLASS Rectangle length width setLength() setWidth() getLength() getWidth() getArea()

6-21 W RITING THE C ODE FOR THE C LASS F IELDS public class Rectangle { private double length; private double width; }

6-22 A CCESS S PECIFIERS An access specifier is a Java keyword that indicates how a field or method can be accessed. Public The member can be accessible by code inside the class or outside. Private The member can not be accessible by code outside the class. The member can be accessed only by methods that are members of the same class.

6-23 H EADER FOR THE SET L ENGTH M ETHOD public void setLength (double len) Access specifier Return Type Parameter variable declaration Method Name Notice the word static does not appear in the method header designed to work on an instance of a class (instance method).

6-24 W RITING AND D EMONSTRATING THE SET L ENGTH M ETHOD /** The setLength method stores a value in the length len The value to store in length. */ public void setLength(double len) { length = len; }

6-25 C REATING A R ECTANGLE OBJECT Rectangle box = new Rectangle(); address 0.0 length: width: The box variable holds the address of the Rectangle object. A Rectangle object

6-26 C ALLING THE SET L ENGTH M ETHOD box.setLength(10.0); address length: width: The box variable holds the address of the Rectangle object. A Rectangle object This is the state of the box object after the setLength method executes. Examples: Rectangle.java, LengthDemo.javaRectangle.javaLengthDemo.java

6-27 W RITING THE GET L ENGTH M ETHOD /** The getLength method returns a Rectangle object's The value in the length field. */ public double getLength() { return length; } Similarly, the setWidth and getWidth methods can be created. Examples: Rectangle.java, LengthWidthDemo.javaRectangle.javaLengthWidthDemo.java

6-28 W RITING AND D EMONSTRATING THE GET A REA M ETHOD /** The getArea method returns a Rectangle object's The product of length times width. */ public double getArea() { return length * width; } Examples: Rectangle.java, RectangleDemo.javaRectangle.javaRectangleDemo.java

6-29 A CCESSOR AND M UTATOR M ETHODS 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.

6-30 A CCESSORS AND M UTATORS 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 getters and setters.

6-31 S TALE D ATA 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.

6-32 UML D ATA T YPE AND P ARAMETER N OTATION UML diagrams are language independent. UML diagrams use an independent notation to show return types, access modifiers, etc. Rectangle - width : double + setWidth(w : double) : void Access modifiers are denoted as: +public -private

6-33 UML D ATA T YPE AND P ARAMETER N OTATION UML diagrams are language independent. UML diagrams use an independent notation to show return types, access modifiers, etc. Rectangle - width : double + setWidth(w : double) : void Variable types are placed after the variable name, separated by a colon.

6-34 UML D ATA T YPE AND P ARAMETER N OTATION UML diagrams are language independent. UML diagrams use an independent notation to show return types, access modifiers, etc. Rectangle - width : double + setWidth(w : double) : void Method return types are placed after the method declaration name, separated by a colon.

6-35 UML D ATA T YPE AND P ARAMETER N OTATION UML diagrams are language independent. UML diagrams use an independent notation to show return types, access modifiers, etc. Rectangle - width : double + setWidth(w : double) : void Method parameters are shown inside the parentheses using the same notation as variables.

6-36 C ONVERTING THE UML D IAGRAM TO C ODE 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. ClassName Fields Methods class header { Fields Methods }

6-37 C ONVERTING THE UML D IAGRAM TO C ODE Rectangle - width : double - length : double + setWidth(w : double) : void + setLength(len : double): void + getWidth() : double + getLength() : double + getArea() : double public class Rectangle { 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; } 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.

6-38 C ONVERTING THE UML D IAGRAM TO C ODE public class Rectangle { 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; } Rectangle - width : double - length : double + setWidth(w : double) : void + setLength(len : double): void + getWidth() : double + getLength() : double + getArea() : double Once the class structure has been tested, the method bodies can be written and tested.

6-39 C LASS L AYOUT C ONVENTIONS The layout of a source code file can vary by employer or instructor. A common layout is: Fields listed first Methods listed second Accessors and mutators are typically grouped.

6-40 I NSTANCE F IELDS AND M ETHODS 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.

6-41 I NSTANCE F IELDS AND M ETHODS Instance fields and instance methods require an object to be created in order to be used. See example: RoomAreas.javaRoomAreas.java Note that each room represented in this example can have different dimensions. Rectangle kitchen = new Rectangle(); Rectangle bedroom = new Rectangle(); Rectangle den = new Rectangle();

6-42 S TATES OF T HREE D IFFERENT R ECTANGLE O BJECTS address length: width: address length: width: address length: width: The kitchen variable holds the address of a Rectangle Object. The bedroom variable holds the address of a Rectangle Object. The den variable holds the address of a Rectangle Object.

6-43 C ONSTRUCTORS Classes can have special methods called constructors. When you create a new instance (a new object) of a class using the new keyword, a constructor for that class is called. Constructors are used to initialize the instance variables (fields) of an object.

6-44 C ONSTRUCTORS 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.

6-45 C ONSTRUCTOR FOR R ECTANGLE C LASS /** len The length of the w The width of the rectangle. */ public Rectangle(double len, double w) { length = len; width = w; } Examples: Rectangle.java, ConstructorDemo.javaRectangle.javaConstructorDemo.java

6-46 C ONSTRUCTORS IN UML In UML, the most common way constructors are defined is: Rectangle - width : double - length : double +Rectangle(len:double, w:double) + setWidth(w : double) : void + setLength(len : double): void + getWidth() : double + getLength() : double + getArea() : double Notice there is no return type listed for constructors.

6-47 U NINITIALIZED L OCAL R EFERENCE V ARIABLES Reference variables can be declared without being initialized. Rectangle box; This statement does not create a Rectangle object, so it is an uninitialized local reference variable. A local reference variable must reference an object before it can be used, otherwise a compiler error will occur. box = new Rectangle(7.0, 14.0); box will now reference a Rectangle object of length 7.0 and width 14.0.

6-48 T HE D EFAULT C ONSTRUCTOR When an object is created, its constructor is always called. If you do not write a constructor, Java provides one when the class is compiled. The constructor that Java provides is known as the default constructor. It sets all of the object’s numeric fields to 0. It sets all of the object’s boolean fields to false. It sets all of the object’s reference variables to the special value null.

6-49 T HE D EFAULT C ONSTRUCTOR The default constructor is a constructor with no parameters, used to initialize an object in a default configuration. The only time that Java provides a default constructor is when you do not write any constructor for a class. See example: First version of Rectangle.javaRectangle.java A default constructor is not provided by Java if a constructor is already written. See example: Rectangle.java with ConstructorRectangle.java

6-50 W RITING Y OUR O WN N O -A RG C ONSTRUCTOR A constructor that does not accept arguments is known as a no-arg constructor. The default constructor (provided by Java) is a no-arg constructor. We can write our own no-arg constructor public Rectangle() { length = 1.0; width = 1.0; }

6-51 T HE S TRING C LASS C ONSTRUCTOR 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("Michael Long"); Because they are used so often, String objects can be created with a shorthand: String name = "Michael Long";

6-52 O VERLOADING M ETHODS AND C ONSTRUCTORS Two or more methods in a class may have the same name as long as their parameter lists are different. When this occurs, it is called method overloading. This also applies to constructors. Method overloading is important because sometimes you need several different ways to perform the same operation.

6-53 O VERLOADED M ETHOD ADD public int add(int num1, int num2) { int sum = num1 + num2; return sum; } public String add (String str1, String str2) { String combined = str1 + str2; return combined; }

6-54 M ETHOD S IGNATURE AND B INDING A method signature consists of the method’s name and the data types of the method’s parameters. The return type is not part of the signature. add(int, int) add(String, String) The process of matching a method call with the correct method is known as binding. The compiler uses the method signature to determine which version of the overloaded method to bind the call to. Signatures of the add methods of previous slide

6-55 R ECTANGLE C LASS C ONSTRUCTOR O VERLOAD If we were to add the no-arg constructor we wrote previously to our Rectangle class in addition to the original constructor we wrote, what would happen when we execute the following calls? Rectangle box1 = new Rectangle(); Rectangle box2 = new Rectangle(5.0, 10.0);

6-56 R ECTANGLE C LASS C ONSTRUCTOR O VERLOAD If we were to add the no-arg constructor we wrote previously to our Rectangle class in addition to the original constructor we wrote, what would happen when we execute the following calls? Rectangle box1 = new Rectangle(); Rectangle box2 = new Rectangle(5.0, 10.0); The first call would use the no-arg constructor and box1 would have a length of 1.0 and width of 1.0. The second call would use the original constructor and box2 would have a length of 5.0 and a width of 10.0.

6-57 S COPE OF I NSTANCE F IELDS Variables declared as instance fields in a class can be accessed by any instance method in the same class as the field. If an instance field is declared with the public access specifier, it can also be accessed by code outside the class, as long as an instance of the class exists.

6-58 S HADOWING 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.

6-59 P ACKAGES AND IMPORT S TATEMENTS Classes in the Java API are organized into packages. Explicit and Wildcard import statements Explicit imports name a specific class import java.util.Scanner; Wildcard imports name a package, followed by an * import java.util.*; The java.lang package is automatically made available to any Java class.

6-60 S OME J AVA S TANDARD P ACKAGES

6-61 O BJECT O RIENTED D ESIGN F INDING C LASSES AND T HEIR R ESPONSIBILITIES 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 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