A First Look At Classes Chapter 6. Procedural Programming In procedural- programming all the program functionality is written in a few modules of code.

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.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 6: A First Look at classes. Object-Oriented Programming  Object-oriented programming is centered on creating objects rather than procedures.
Chapter 6. Overloading Methods and Constructors  Two or more methods in a class may have the same name as long as their parameter lists are different.
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.
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
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.
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
Chapter 6: A First Look at Classes
UML Basics & Access Modifier
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
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.
I NTRODUCTION TO PROGRAMMING 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.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Copyright © 2012 Pearson Education, Inc. Chapter 9 Classes and Multiform Projects.
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 3 (B) 3.5 – 3.7.  Variables declared in a function definition’s body are known as local variables and can be used only from the line of their.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
CSci 162 Lecture 10 Martin van Bommel. Procedures vs Objects Procedural Programming –Centered on the procedures or actions that take place in a program.
Page 4.1 – Autumn 2010Steffen Vissing Andersen SDJ I1, Autumn 2010 Agenda – Session 4 – 7. September 2009 Java fundamentals, checkpoint from chapter 2.
© 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 © 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,
Separating Class Specification tMyn1 Separating Class Specification from Implementation Usually class declarations are stored in their own header files.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
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.
Powerpoint slides from A+ Computer Science Modified by Mr. Smith for his course.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Unified Modeling Language
Lecture 9: Object and Classes Michael Hsu CSULA. 2 OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 26, 2009.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 9 Introduction of Object Oriented Programming.
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.
A Second Look at Classes and Objects - 1 Static Class Members
Pointer to an Object Can define a pointer to an object:
Procedural and Object-Oriented Programming
Chapter 3 Classes & Objects
A first Look at Classes.
Lecture 6 D&D Chapter 7 & 8 Intro to Classes and Objects Date.
Chapter 3: Using Methods, Classes, and Objects
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:

A First Look At Classes Chapter 6

Procedural Programming In procedural- programming all the program functionality is written in a few modules of code or maybe one module (depending on the program). These modules depend on one another and sometimes changing a line of code requires you to rewrite the whole module again and maybe the whole program.

In Object-Oriented Programming programmers write independent parts of a program called classes. Each class represents a part of the program functionality and these classes can be assembled to form a program. When you need to change some of the program functionality all you have to do is to replace the target class which may contain the problem that needs change Object-Oriented Programming

The World’s objects and classes In our world we have classes and objects for those classes. Everything in our world is considered to be an object. For example, people are objects, animals are objects too, minerals are objects; everything in the world is an object. Easy, right? But what about classes?

In our world we have to differentiate between objects that we are living with. So we must understand that there are classifications (this is how they get the name and the concepts of the Class) for all of those objects. For example, I'm an object, David is object too, Maria is another object. So we are from a people class (or type). I have a dog called Rover so it's an object. My friend's dog, Ntombomsi, is also an object so they are from a Dogs class (or type). The World’s objects and classes

In our world we have classifications for objects and every object must be from some classification. So, a Class is a way for describing some properties and functionalities or behaviors of a group of objects. In other words, the class is considered to be a template for some objects. So maybe we will create a class called person which is a template of the functionality and the properties of persons. The World’s objects and classes

Programmer’s objects and classes The class: A building block that contains the properties and functionalities that describe some group of objects. We can create a class Person that contains:

Programmer’s objects and classes The properties of any normal person on the earth like: hair color, age, height, weight, eye color.

Programmer’s objects and classes The properties of any normal person on the earth like: hair color, age, height, weight, eye color.

Programmer’s objects and classes The properties of any normal person on the earth like: hair color, age, height, weight, eye color.

Programmer’s objects and classes The properties of any normal person on the earth like: hair color, age, height, weight, eye color.

Programmer’s objects and classes The properties of any normal person on the earth like: hair color, age, height, weight, eye color.

Programmer’s objects and classes The functionalities or behaviors of any normal person on the earth like: drink water, eat, go to the work.

Programmer’s objects and classes The functionalities or behaviors of any normal person on the earth like: drink water, eat, go to the work.

Programmer’s objects and classes The functionalities or behaviors of any normal person on the earth like: drink water, eat, go to the work.

Programmer’s objects and classes The functionalities or behaviors of any normal person on the earth like: drink water, eat, go to work.

When you create an object you can specify the properties of that object. One object can have different properties (hair color, age, height, weight) than another object. For example, I have brown eyes and you have green eyes. When I create 2 objects I will specify a brown color for my object's eye color property and I will specify a green color for your object's eye color property. Programmer’s objects and classes

Variables declared in a class store the data for each instance. What does this mean? It means that when you instantiate this class (that is, when you create an object of this class) the object will allocate memory locations to store the data of its variables. Programmer’s objects and classes

This is our simple class which contains 2 variables (fields): public class Person { private int age; private String hairColor; } public class Person { private int age; private String hairColor; } Programmer’s objects and classes

6-20 Access Specifiers An access specifier is a Java keyword that indicates how a field or method can be accessed. public ◦ When the public access specifier is applied to a class member, the member can be accessed by code inside the class or outside. private ◦ When the private access specifier is applied to a class member, the member cannot be accessed by code outside the class. The member can be accessed only by methods that are members of the same class.

It is a common practice to make all of a class’s fields private and to provide public methods for accessing and changing those fields. Programmer’s objects and classes

A method that gets a value from a class’s field but does not change it is known as an accessor method (getter). public int getAge() { return age; } public int getAge() { return age; } Programmer’s objects and classes

A method that stores a value in a field or changes the value in a field in some other way is known as a mutator method (setter). public void setAge(int Age) { age = Age; } public void setAge(int Age) { age = Age; } Programmer’s objects and classes

public class Person { private int age; private String hairColor; public void setAge(int Age) { age = Age; } public void setHairColor(String colorHair) { hairColor = colorHair; } public int getAge() { return age; } public String getHairColor() { return hairColor; } public class Person { private int age; private String hairColor; public void setAge(int Age) { age = Age; } public void setHairColor(String colorHair) { hairColor = colorHair; } public int getAge() { return age; } public String getHairColor() { return hairColor; } private fields of the class Person

public class Person { private int age; private String hairColor; public void setAge(int Age) { age = Age; } public void setHairColor(String colorHair) { hairColor = colorHair; } public int getAge() { return age; } public String getHairColor() { return hairColor; } public class Person { private int age; private String hairColor; public void setAge(int Age) { age = Age; } public void setHairColor(String colorHair) { hairColor = colorHair; } public int getAge() { return age; } public String getHairColor() { return hairColor; } Access specifier Return Type Method Name Notice the word static does not appear in the method header designed to work on an instance of a class (instance method). Parameter variable declaration

public class Person { private int age; private String hairColor; public void setAge(int Age) { age = Age; } public void setHairColor(String colorHair) { hairColor = colorHair; } public int getAge() { return age; } public String getHairColor() { return hairColor; } public class Person { private int age; private String hairColor; public void setAge(int Age) { age = Age; } public void setHairColor(String colorHair) { hairColor = colorHair; } public int getAge() { return age; } public String getHairColor() { return hairColor; } Mutators Accessors

public class Person { private int age; private String hairColor; public void setAge(int Age)Person jake = new Person(); {jake.setAge(10); age = Age; } public void setHairColor(String colorHair) { hairColor = colorHair; } public int getAge() { return age; } public String getHairColor() { return hairColor; } public class Person { private int age; private String hairColor; public void setAge(int Age)Person jake = new Person(); {jake.setAge(10); age = Age; } public void setHairColor(String colorHair) { hairColor = colorHair; } public int getAge() { return age; } public String getHairColor() { return hairColor; }

public class Person { private int age; private String hairColor; public void setAge(int Age)Person jake = new Person(); {jake.setAge(10); age = Age; } public void setHairColor(String colorHair)jake.setHairColor(“Brown”); { hairColor = colorHair; } public int getAge() { return age; } public String getHairColor() { return hairColor; } public class Person { private int age; private String hairColor; public void setAge(int Age)Person jake = new Person(); {jake.setAge(10); age = Age; } public void setHairColor(String colorHair)jake.setHairColor(“Brown”); { hairColor = colorHair; } public int getAge() { return age; } public String getHairColor() { return hairColor; }

public class Person { private int age; private String hairColor; public void setAge(int Age)Person jake = new Person(); {jake.setAge(10); age = Age; } public void setHairColor(String colorHair)jake.setHairColor(“Brown”); { hairColor = colorHair; } public int getAge()jake.getAge(); { return age; } public String getHairColor() { return hairColor; } public class Person { private int age; private String hairColor; public void setAge(int Age)Person jake = new Person(); {jake.setAge(10); age = Age; } public void setHairColor(String colorHair)jake.setHairColor(“Brown”); { hairColor = colorHair; } public int getAge()jake.getAge(); { return age; } public String getHairColor() { return hairColor; }

public class Person { private int age; private String hairColor; public void setAge(int Age)Person jake = new Person(); {jake.setAge(10); age = Age; } public void setHairColor(String colorHair)jake.setHairColor(“Brown”); { hairColor = colorHair; } public int getAge()jake.getAge(); { return age; } public String getHairColor()jake.getHairColor(); { return hairColor; } public class Person { private int age; private String hairColor; public void setAge(int Age)Person jake = new Person(); {jake.setAge(10); age = Age; } public void setHairColor(String colorHair)jake.setHairColor(“Brown”); { hairColor = colorHair; } public int getAge()jake.getAge(); { return age; } public String getHairColor()jake.getHairColor(); { return hairColor; }

public static void main(String[] args) { Person jake = new Person(); Person david = new Person(); jake.setAge(20); jake.setHairColor("Brown"); david.setAge(30); david.setHairColor("Blonde"); System.out.println("Jake's age is " + jake.getAge() + " and his hair color is " + jake.getHairColor()); System.out.println("David's age is " + david.getAge() + " and his hair color is " + david.getHairColor()); } public static void main(String[] args) { Person jake = new Person(); Person david = new Person(); jake.setAge(20); jake.setHairColor("Brown"); david.setAge(30); david.setHairColor("Blonde"); System.out.println("Jake's age is " + jake.getAge() + " and his hair color is " + jake.getHairColor()); System.out.println("David's age is " + david.getAge() + " and his hair color is " + david.getHairColor()); }

6-32 Building a Rectangle 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-33 Building a Rectangle 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-34 UML Diagram 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-35 UML Diagram for Rectangle class Rectangle length width setLength() setWidth() getLength() getWidth() getArea()

6-36 Writing the Code for the Class Fields public class Rectangle { private double length; private double width; }

6-37 public class Rectangle { private double length; private double width; public void setLength(double len)Rectangle box = new Rectangle(); {box.setLength(12.0); length = len; } public void setWidth(double w) { width = w; } public double getLength() { return length; } public double getWidth() { return width; } public double getArea() { return length * width; } public class Rectangle { private double length; private double width; public void setLength(double len)Rectangle box = new Rectangle(); {box.setLength(12.0); length = len; } public void setWidth(double w) { width = w; } public double getLength() { return length; } public double getWidth() { return width; } public double getArea() { return length * width; }

6-38 public class Rectangle { private double length; private double width; public void setLength(double len)Rectangle box = new Rectangle(); {box.setLength(12.0); length = len; } public void setWidth(double w)box.setWidth(10.0); { width = w; } public double getLength() { return length; } public double getWidth() { return width; } public double getArea() { return length * width; } public class Rectangle { private double length; private double width; public void setLength(double len)Rectangle box = new Rectangle(); {box.setLength(12.0); length = len; } public void setWidth(double w)box.setWidth(10.0); { width = w; } public double getLength() { return length; } public double getWidth() { return width; } public double getArea() { return length * width; }

6-39 public class Rectangle { private double length; private double width; public void setLength(double len)Rectangle box = new Rectangle(); {box.setLength(12.0); length = len; } public void setWidth(double w)box.setWidth(10.0); { width = w; } public double getLength()box.getLength(); { return length; } public double getWidth() { return width; } public double getArea() { return length * width; } public class Rectangle { private double length; private double width; public void setLength(double len)Rectangle box = new Rectangle(); {box.setLength(12.0); length = len; } public void setWidth(double w)box.setWidth(10.0); { width = w; } public double getLength()box.getLength(); { return length; } public double getWidth() { return width; } public double getArea() { return length * width; }

6-40 public class Rectangle { private double length; private double width; public void setLength(double len)Rectangle box = new Rectangle(); {box.setLength(12.0); length = len; } public void setWidth(double w)box.setWidth(10.0); { width = w; } public double getLength()box.getLength(); { return length; } public double getWidth()box.getWidth(); { return width; } public double getArea() { return length * width; } public class Rectangle { private double length; private double width; public void setLength(double len)Rectangle box = new Rectangle(); {box.setLength(12.0); length = len; } public void setWidth(double w)box.setWidth(10.0); { width = w; } public double getLength()box.getLength(); { return length; } public double getWidth()box.getWidth(); { return width; } public double getArea() { return length * width; }

6-41 public class Rectangle { private double length; private double width; public void setLength(double len)Rectangle box = new Rectangle(); {box.setLength(12.0); length = len; } public void setWidth(double w)box.setWidth(10.0); { width = w; } public double getLength()box.getLength(); { return length; } public double getWidth()box.getWidth(); { return width; } public double getArea() box.getArea(); { return length * width; } public class Rectangle { private double length; private double width; public void setLength(double len)Rectangle box = new Rectangle(); {box.setLength(12.0); length = len; } public void setWidth(double w)box.setWidth(10.0); { width = w; } public double getLength()box.getLength(); { return length; } public double getWidth()box.getWidth(); { return width; } public double getArea() box.getArea(); { return length * width; }

6-42 public class RectangleDemo { public static void main(String[] args) { // Create a Rectangle object. Rectangle box = new Rectangle(); // Set length to 10.0 and width to box.setLength(10.0); box.setWidth(20.0); // Display the length. System.out.println("The box's length is " + box.getLength()); // Display the width. System.out.println("The box's width is " + box.getWidth()); // Display the area. System.out.println("The box's area is " + box.getArea()); } public class RectangleDemo { public static void main(String[] args) { // Create a Rectangle object. Rectangle box = new Rectangle(); // Set length to 10.0 and width to box.setLength(10.0); box.setWidth(20.0); // Display the length. System.out.println("The box's length is " + box.getLength()); // Display the width. System.out.println("The box's width is " + box.getWidth()); // Display the area. System.out.println("The box's area is " + box.getArea()); }

6-43 Creating a Rectangle object Rectangle box = new Rectangle (); address 0.0 length: width: The box variable holds the address of the Rectangle object. A Rectangle object

6-44 Calling the setLength Method 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.

6-45 Accessor and Mutator Methods 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-46 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 getters and setters.

6-47 Stale Data Some data is the result of a calculation. Consider the area of a rectangle. ◦ length × 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.

6-48 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.

6-49 UML Data Type and Parameter Notation Rectangle - width : double + setWidth(w : double) : void Access modifiers are denoted as: +public -private UML diagrams are language independent. UML diagrams use an independent notation to show return types, access modifiers, etc.

6-50 UML Data Type and Parameter Notation Rectangle - width : double + setWidth(w : double) : void Variable types are placed after the variable name, separated by a colon. UML diagrams are language independent. UML diagrams use an independent notation to show return types, access modifiers, etc.

6-51 UML Data Type and Parameter Notation Rectangle - width : double + setWidth(w : double) : void Method return types are placed after the method declaration name, separated by a colon. UML diagrams are language independent. UML diagrams use an independent notation to show return types, access modifiers, etc.

6-52 UML Data Type and Parameter Notation Rectangle - width : double + setWidth(w : double) : void Method parameters are shown inside the parentheses using the same notation as variables. UML diagrams are language independent. UML diagrams use an independent notation to show return types, access modifiers, etc.

6-53 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. ClassName Fields Methods class header { Fields Methods }

6-54 Converting the UML Diagram to Code 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-55 Converting the UML Diagram to Code 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-56 Class Layout Conventions 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. There are tools that can help in formatting layout to specific standards.

6-57 Instance Fields and Methods 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-58 Instance Fields and Methods 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-59 States of Three Different Rectangle Objects 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-60 Constructors Classes can have special methods called constructors. A constructor is a method that is automatically called when an object is created. Constructors are used to perform operations at the time an object is created. Constructors typically initialize instance fields and perform other object initialization tasks.

6-61 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.

6-62 Constructor for Rectangle Class private double length; private double width; public Rectangle(double len, double w) { length = len; width = w; } Call: Rectangle box = new Rectangle(5.0,15.0);

6-63 Constructors 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-64 Uninitialized Local Reference Variables 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-65 The Default Constructor 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-66 The Default Constructor 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. A default constructor is not provided by Java if a constructor is already written.

6-67 Writing Your Own No-Arg Constructor 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-68 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("Michael Long");

6-69 The String Class Constructor This creates a new reference variable name that points to a String object that represents the name “Michael Long” Because they are used so often, String objects can be created with a shorthand: String name = "Michael Long";

6-70 Overloading Methods and Constructors 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-71 Overloaded Method 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-72 Method Signature and Binding A method signature consists of the method’s name and the data types of the method’s parameters, in the order that they appear. 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-73 Rectangle Class Constructor Overload 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-74 Rectangle Class Constructor Overload 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-75 The BankAccount Example BankAccount.java AccountTest.java BankAccount -balance:double +BankAccount() +BankAccount(startBalance:double) +BankAccount(str:String) +deposit(amount:double):void +deposit(str:String):void +withdraw(amount:double):void +withdraw(str:String):void +setBalance(b:double):void +setBalance(str:String):void +getBalance():double Overloaded Constructors Overloaded deposit methods Overloaded withdraw methods Overloaded setBalance methods

6-76 Scope of Instance Fields 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-77 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. public void setLength(double len) { int length; length = len;; }

6-78 Packages and import Statements 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-79 Some Java Standard Packages

6-80 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

6-81 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