Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 Chapter 6 A First Look at Classes

2 2 Contents 1. Classes and objects 2. Instance Fields and Methods 3. Constructors 4. Overloading Methods and Constructors 5. Scope of Instance Fields 6. Packages and import Statements 7. Focus on Object-Oriented Design: Finding the Classes and Their Responsibilities

3 3 1. Classes and Objects Procedures typically operate on data items that are separate from the procedures. Procedural programming is centered on creating procedures. Object oriented programming is centered on creating objects. An object is a software entity that contains data and procedures. Data: Fields Procedures: Methods

4 4 1. Classes and Objects An object's fields are called attributes. A class is the blueprint for an object. It specifies the fields and methods a particular type of object has. From the class, one or more objects may be created.

5 5 1. Classes and Objects Object oriented programming addresses the problem of code/data separation through: Encapsulation Data Hiding Encapsulation refers to the combining of data and code into a single object. Data hiding refers to an object's ability to hide its data from code that is outside the object. Only the object's methods may directly access and make changes to the object's data. An object hides its data, but allows outside code to access its methods.

6 6 1. Classes and Objects Object reusability An object is not a stand-alone program, but is used by programs that its services. An everyday example of an object Your alarm clock: An object The current second (0-59) The current minute (0-59) The current hour (1-12) The time the alarm is set for (a valid hour and minute) Whether the alarm is on or off (“on” or “off”)

7 7 1. Classes and Objects Fields are merely data values that define the state of the alarm clock is currently in. The user cannot directly manipulate these fields because they are private. To change a field's value, we must use one of the object's methods. Some of the alarm clock object's methods Set time Set alarm time Turn alarm on Turn alarm off These methods can be activated by users, who are outside the alarm clock. They are public methods.

8 8 1. Classes and Objects The alarm clock also has private methods, which are parts of the object's private, internal workings. External entities (such as you, the user of the alarm clock) do not have directly access to the alarm clock's private methods. The object is designed to execute these methods automatically and hide the details from you. Some of the alarm clock object's private methods Increment the current second Increment the current minute Increment the current hour Sound alarm

9 9 1. Classes and Objects Before an object is created, it must be designed by a programmer. The programmer determines the fields and the methods that are necessary, and then creates a class. Think of a class as a “blueprint” that objects may be created from. A class is not an object, but it is a description of an objects. When the program is running, it can use the class to create, in memory, as many objects as needed. Each object that is created from a class is called an instance of the class.

10 10 1. Classes and Objects Insect class housefly object mosquito object The Insect class describes the fields and methods that a particular type of object may have. The housefly object is an instance of the Insect class. It has the fields and methods described by the Insect class. The mosquito object is an instance of the Insect class. It has the fields and methods described by the Insect class. All of the objects that are created from the same class will have the fields ad methods described by the class.

11 11 Objects versus Primitive Variables Java primitive data types: byte, short, int, long, char, float, double, boolean Primitive variables are storage locations in the computer's memory. A primitive data type is called “primitive” because a variable created with a primitive data type has no built-in capabilities other than storing a value.

12 12 Objects versus Primitive Variables String class allows you to create String objects In addition to storing strings, String object s have numerous methods that perform operations on the strings they hold. String name = “Peter”; stringSize = name.length(); address “ Peter ” A String object The name variable holds the address of a String object.

13 13 Building a Simple Class Step by Step Write a class named Rectangle. Each object that is created from the Rectangle class will be able to hold data about a rectangle. A Rectangle object will have the following fields length : Hold the rectangle's length width : Hold the rectangle's width The Rectangle class will also have the following methods setLength : Store a value in an object's length field setWidth : Store a value in an object's width field getLength : Return the value in an object's length field

14 14 Building a Simple Class Step by Step getWidth : Return the value in an object's width field. getArea : Return the area of the rectangle. When designing a class it is often helpful to draw a UML diagram. UML stands for Unified Modeling Language. It provides a set of standard diagrams for graphically depicting object oriented systems.

15 15 UML Diagram for a Class The general layout of a UML diagram for a class: The diagram is a box that is divided into three sections. The top section is where you write the name of the class. The middle section holds a list of the class's fields. The bottom section holds a list of the class's methods.

16 16 UML Diagram for a Class UML diagram for the Rectangle class Rectangle length width setLength() SetWidth() GetLength() GetWidth() getArea()

17 17 Writing the Code for a Class Create a file named Rectangle.java In the Rectangle.java file, we start by writing a general class skeleton as follows public class Rectangle { } The public access specifier indicates that the class will be publicly available to code outside the Rectangle.java file.

18 18 Writing the Code for the Class Fields We will write the code for the class's two fields width and length. We use variables of the double data types. public class Rectangle { private double length; private double width; }

19 19 Writing the Code for the Class Fields Access specifier private : When the private access specifier is applied to a class member, the member cannot be accessed by the code outside the class. The member can be accessed only by methods that are members of the same class. public : When the public access specifier is applied to a class member, the member can be accessed by the code inside the class or outside.

20 20 Writing the setLength Method public class Rectangle { private double length; private double width; /** The setLength method stores a value in the length field. @param len The value to store in length. */ public void setLength(double len) { length = len; } }

21 21 Using Rectangle Class

22 22 Using Rectangle Class

23 23 Using Rectangle Class

24 24 Using Rectangle Class

25 25 Using Rectangle Class Rectangle box = new Rectangle(); box.setLength(10.0); box.setWidth(20.0); address length width A Rectangle object The box variable holds the address of a Rectangle object. 0.0 address length width A Rectangle object The box variable holds the address of a Rectangle bject. 10. 0 0.0 address length width A Rectangle object The box variable holds the address of a Rectangle object. 10. 0 20. 0

26 26 Accessor and Mutator Methods 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. A method that gets a value from a class's field but does not change it is known an accessor method (getter). A method that stores a value in a field or changes the value of a field is known as a mutator method (setter). In the Rectangle class getLength, getWidth : accessor methods setLength, setWidth : mutator methods

27 27 Avoiding Stale Data In the Rectangle class, the getArea method returns the result of a calculation. The area of the rectangle is not stored in a field. Why? The area is not stored in a field because it could potentially become stale. When the value of an item is dependent on other data and that item is not updated when the other data is changed, it is said that the item has become stale.

28 28 Avoiding Stale Data If the area is stored in a field, the value of this field becomes incorrect as soon as either the length or width fields changed. When designing a class, you should take care not to store in a field calculated data that can potentially become stale. Instead, provide a method that returns the result of the calculation.

29 29 Showing Access Specification in UML Diagrams In a UML diagram, A – character before a member name indicates that it is private. A + character before a member name indicates that it is public. Rectangle - length - width + setLength() + setWidth() + getLength() + getWidth() + getArea()

30 30 Data Type and Parameter Notation in UML Diagrams The UML diagram also provides notation that you may use to indicate Data types of fields, methods Parameter variables Return type of a method Rectangle - length: double - width: double + setLength(len: double): void + setWidth(w: double): void + getLength(): double + getWidth(): double + getArea(): double

31 31 Layout of Class Members Typical layout of class members public class ClassName { } Field declarations Methods definitions

32 32 Checkpoint 6.3 6.5 6.6 6.7 6.8 6.9

33 33 2. Instance Fields and Methods Each instance of a class has its own set of fields, which are known as instance fields or instance variables. You can create several instances of a class and store different values in each instance's fields. The methods that operate on an instance of a class are known as instance methods. Instance methods do not have the keyword static in their headers.

34 34 2. Instance Fields and Methods Rectangle kitchen = new Rectangle(); Rectangle bedroom = new Rectangle(); Rectangle den = new Rectangle(); address length width A Rectangle object The box variable holds the address of a Rectangle bject. 0.0 address length width The bedroom variable holds the address of a Rectangle bject. 0.0 address length width The den variable holds the address of a Rectangle bject. 0.0 A Rectangle object

35 35 2. Instance Fields and Methods kitchen.setLength(10.0); kitchen.setWidth(14.0); bedroom.setLength(15.0); bedroom.setWidth(12.0); den.setLength(20.0); den.setWidth(30.0); address The den variable holds the address of a Rectangle bject. A Rectangle object address Length width The den variable holds the address of a Rectangle bject. A Rectangle object 20. 0 30. 0 address A Rectangle object address Length width A Rectangle object 15. 0 12. 0 address A Rectangle object address Length width A Rectangle object 10. 0 14. 0 The bedroom variable hold the address of a Rectangle object. The kitchen variable hold the address of a Rectangle object.

36 36 Checkpoint 6.10 Assume that r1 and r2 are variables that reference Rectangle objects, and the following statements are executed: r1.setLength(5.0); r2.setLength(10.0); r1.setWidth(20.0); r2.setWidth(15.0); Fill in the boxes in the figure that represent each object's length and width fields.

37 37 Checkpoint address length width 0.0 address length width 0.0 A Rectangle object r1 r2

38 38 Checkpoint r1.setLength(5.0); r2.setLength(10.0); r1.setWidth(20.0); r2.setWidth(15.0); address length width 0.0 address length width 0.0 A Rectangle object r1 r2 5.0 10. 0 20. 0 15. 0

39 39 3. Constructors A constructor Has the same name as the class. A method that is automatically called when an instance of a class is created. Performs initialization or setup operations Storing initial values in instance fields. It is called a constructor because it helps construct an object. The constructor's header does not specify a return type.

40 40 3. Constructors Write a constructor in the class Rectangle: The constructor has the name Rectangle. The constructor has two arguments The length of the rectangle The width of the rectangle Two arguments are then assigned to the length and width fields.

41 41 3. Constructors This constructor accepts two arguments.

42 42 3. Constructors Constructor's header does not specify a return type – not even void. The method header for a constructor AccessSpecifier ClassName(Parameters … ) Showing Constructors in a UML Diagram Rectangle - length: double - width: double + Rectangle(len: double, w: double) + setLength(len: double): void + setWidth(w: double): void + getLength(): double + getWidth(): double + getArea(): double

43 43 3. Constructors

44 44 Uninitialized Local Reference Variables Reference variables can be declared without being initialized. Rectangle box; Does not create a Rectangle object. Only declares a variable named box. Does not reference to any Rectangle object. It is an uninitialized local reference variable. box = new Rectangle(7.0, 14.0); Creates a Rectangle object in memory. box references to this object.

45 45 Uninitialized Local Reference Variables Rectangle box; box = new Rectangle(7.0, 14.0); Rectangle box = new Rectangle(7.0, 14.0); Be careful when using uninitialized reference variables: Reference variables must be initialized or assigned a value before they can be used.

46 46 The Default Constructor When an object is created, its constructor is always called. If we do not write a constructor Java automatically provides one. It is known as default constructor. The default constructor Does not accept arguments Sets all object's numeric fields to 0 Sets boolean fields to false. Sets fields that are reference variables to null.

47 47 The Default Constructor We wrote no constructor for the Rectangle class Rectangle r = new Rectangle(); // Calls the default constructor Now we wrote our own constructor for the Rectangle class Rectangle r = new Rectangle(); // Error! Java does not provide the default constructor. We must call the constructor we wrote.

48 48 No-Argument Constructor A constructor that does not accept arguments is known as a no-argument constructor. The default constructor is a no-argument constructor. We can write our own no-argument constructor. public Rectangle() { length = 1.0; width = 1.0; } Rectangle r = new Rectangle(); ● Calls the no-argument constructor

49 49 The String Class Constructor The String class has a constructor. Accepts a string literal as its argument. Uses the string literal to initialize the String object. String name = new String(“Pham Dai Xuan”); Java provides the shortcut notation for creating and initializing String objects. String name = “Pham Dai Xuan”;

50 50 Checkpoint 6.11 How is a constructor named? A constructor must have the same name as the class. 6.12 What is a constructor's return type? A constructor does not have a return type.

51 51 Checkpoint 6.13 Assume that the following is a constructor, which appears in a class: ClassABC(int number) { item = number; } a) What is the name of the class ? ClassABC b) Write a statement that create an object and passes the value 25 as an argument to the constructor. ClassABC abc = new ClassABC(25);

52 52 Overloading Methods and Constructors Problem: Write a Java class that has seven methods 1) Calculate the sum of two integer numbers. 2) Calculate the sum of two double numbers. 3) Calculate the sum of an integer number and a double number. 4) Calculate the sum of a double number and an integer number. 5) Combine two strings. 6) Combine a double with a string 7) Combine a String with a double

53 53 Overloading Methods and Constructors UML class diagram Addition + addInt(num1: int, num2: int): int + addDouble(num1: double, num2: double): double + addIntDouble(num1: int, num2: double): double + addDoubleInt(num1: double, num2: int): double + addString(str1: String, str2: String): String + addDoubleString(num: double, str: String): String + addStringDouble(str: String, num: double): String

54 54 Overloading Methods and Constructors

55 55 Overloading Methods and Constructors

56 56 Overloading Methods and Constructors

57 57 Overloading Methods The Addition class is not easy to use. We have to choose the right method for each case. How about the + operator in Java 10 + 2 5.3 + 7.3 2 + 5.3 3.4 + 2 “Hello “ + “world!” “10.5 “ + “kg” “Weight (kg): “ + 20.5 We use the same + operator as long as their operands are different.

58 58 Overloading Methods In Java, two or more methods in a class may have the same name as long as their parameter lists are different. Overloading methods When a method is overloaded, it means that multiple methods in the same class have the same name, but use different types of parameters. Method overloading is used when several different ways to perform the same operation.

59 59 Overloading Methods UML class diagram Addition + add(num1: int, num2: int): int + add(num1: double, num2: double): double + add(num1: int, num2: double): double + add(num1: double, num2: int): double + add(str1: String, str2: String): String + add(num: double, str: String): String + add(str: String, num: double): String

60 60 Overloading Methods

61 61 Overloading Methods

62 62 Overloading Methods

63 63 Overloading Methods Java uses a method's signature to distinguish it from other methods of the same name. A method's signature The method name The data type of the method's parameters add(int, int) add(String, String) add(double, String) add(String, double)

64 64 Overloading Methods Note that the method's return type is not part of the signature. public String add(String str1, String str2) { return str1 + str2; } public int add(String str1, String str2) { return Integer.parseInt(str1) + Integer.parseInt(str2); } These two methods can not be added to the same class.

65 65 Overloading Constructors Constructors can be overloaded. A class can have more than one constructors. The rules for overloading constructors are the same for overloading methods. public Rectangle() public Rectangle(double l, double w) { { length = 0.0; length = l; width = 0.0; width = w; } } Rectangle box1 = new Rectangle(); Rectangle box2 = new Rectangle(5.0, 10.0);

66 66 The BankAccount Class A bank account is simulated by an object of the BankAccount class. The BankAccount object allows us To have a starting balance To make deposits To make withdrawals To get the current balance

67 67 The BankAccount Class UML class diagram BalanceAccount - 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

68 68 The BankAccount Class

69 69 The BankAccount Class

70 70 The BankAccount Class

71 71 The BankAccount Class

72 72 The BankAccount Class

73 73 The BankAccount Class

74 74 5. Scope of Instance Fields A variable's scope is the part of a program where the variable may be accessed by its name. Location of a variable's declaration determines the variable's scope. Instance fields can be accessed by any instance method in the same class as the field. If the instance field is declared with the public access specifier, it can also be accessed by the code outside the class.

75 75 Shadowing We cannot have two local variables with the same name in the same scope. A parameter variable is, in essence, a local variable. We cannot give a parameter variable and a local variable in the same method the same name. However, we can have a local variable or a parameter variable with the same name as a field. The name of the local variable or parameter variable shadows the name of the field.

76 76 Shadowing For example, assume that the Rectangle class's setLength method had been written in the following manner: public void setLength(double len) { double length;// local variable length = len;// length : local variable }

77 77 Checkpoint 6.14 Is it required that overloaded methods have different return values, different parameter lists, or both? Different parameter lists 6.15 What is a method's signature? A method's signature is used to distinguish it from other methods of the same name. A method's signature consists of Method name Data types of the method's parameters, in order that they appear.

78 78 Checkpoint Look at the following class: public class Checkpoint { public void message(int x) { System.out.print(“This is the 1 st version ”); System.out.print(“of the method.”); } public void message(String x) { System.out.print(“This is the 2 nd version ”); System.out.print(“of the method.”); } }

79 79 Checkpoint What will the following code display? Checkpoint cp = new Checkpoint(); cp.message(“1”); cp.message(1); This is the 2 nd version of the method. This is the 1 st version of the method.

80 80 Checkpoint 6.17 How many default constructors may a class have? 1

81 81 Packages and import Statements The classes in the Java API are organized into packages. An import statement tells the compiler which package a class is located in. A package is simply a group of related classes. Each package has a name. We have to import an API class in order to use it.

82 82 Explicit and Wildcard import Statements An explicit import statement identifies the package location of a single class. import java.util.Scanner; A wildcard import statement tells the compiler to import all of the classes in a package. import java.util.*;


Download ppt "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."

Similar presentations


Ads by Google