Presentation is loading. Please wait.

Presentation is loading. Please wait.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Chapter 8 Objects and Classes.

Similar presentations


Presentation on theme: "Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Chapter 8 Objects and Classes."— Presentation transcript:

1 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Chapter 8 Objects and Classes 1

2 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections, loops, methods, and arrays. However, these Java features are not sufficient for developing graphical user interfaces and large scale software systems. Suppose you want to develop a graphical user interface as shown below. How do you program it? 2

3 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Objectives To describe objects and classes, and use classes to model objects (§8.2). To use UML graphical notations to describe classes and objects (§8.2). To demonstrate defining classes and creating objects (§8.3). To create objects using constructors (§8.4). To access objects via object reference variables (§8.5). To define a reference variable using a reference type (§8.5.1). To access an object’s data and methods using the object member access operator (.) (§8.5.2). To define data fields of reference types and assign default values for an object’s data fields (§8.5.3). To distinguish between object reference variables and primitive data type variables (§8.5.4). To use classes Date, Random, and JFrame in the Java library (§8.6). To distinguish between instance and static variables and methods (§8.7). To define private data fields with appropriate get and set methods (§8.8). To encapsulate data fields to make classes easy to maintain (§8.9). To develop methods with object arguments and differentiate between primitive-type arguments and object-type arguments (§8.10). To store and process objects in arrays (§8.11). 3

4 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 4 OO Programming Concepts Object-oriented programming (OOP) involves programming using Classes and Objects. A class is used to describe something in the world, such as occurrences, things, external entities, roles, organization units, places or structures. A class describes the structure and behavior of a set of similar objects. It is often described as a template, generalized description, pattern or blueprint for an object, as opposed to the actual object, itself.

5 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 5 Once a class of items is defined, a specific instance of the class can be defined. An instance is also called “object”. An object has a unique identity, state, and behaviors. The state of an object consists of a set of data fields (also known as properties) with their current values. The behavior of an object is defined by a set of methods, in other words what the object does. In other words an object is a software bundle of variables and related methods.

6 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 6 The table gives some examples of classes and objects Class and Object Example Real World Objects

7 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 7 UML Class and Object Diagrams: A class diagram is simply a rectangle divided into three compartments. The topmost compartment contains the name of the class. The middle compartment contains a list of attributes (member variables), and the bottom compartment contains a list of operations (member functions). The purpose of a class diagram is to show the classes within a model.

8 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 8 Kinds of classes: Standard Class: Don’t reinvent the wheel. When there are existing objects that satisfy our needs, use them. Learning how to use standard Java classes is the first step toward mastering OOP. Some of the standard classes are JOptionPane, String, Scanner etc Programmer defined Class: Using just the String, JOptionPane, Scanner, JFrame and other standard classes will not meet all of our needs. We need to be able to define our own classes customized for our applications. Classes we define ourselves are called programmer- defined classes

9 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 9 class { } Template for Class Definition Import Statements Class Comment Class Name Data Members Methods (incl. Constructor) Methods (incl. Constructor)

10 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Example of a Class 10

11 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Object Declaration 11 More Examples Student jan; Object Name One object is declared here. Class Name This class must be defined before this declaration can be stated. Class Name This class must be defined before this declaration can be stated. Accountcustomer; Studentjan, jim, jon; Vehiclecar1, car2;

12 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Object Creation 12 jan = new Student ( ) ; More Examples Object Name Name of the object we are creating here. Class Name An instance of this class is created. Argument No arguments are used here. customer = new Account(); jon= new Student(“John Java”); car1= new Vehicle( );

13 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Declaration vs. Creation 13 Student hussain; hussain = new Student( ); Student hussain; hussain = new Student( ); 1. The identifier hussain is declared and space is allocated in memory. 2. A Student object is created and the identifier hussain is set to refer to it. 1 2 hussain 1 : Student 2 Declaration and Creation in one step Student hussain= new Student(); Create an object Assign object reference

14 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 14 Accessing members of a class. (dot) operator is used to access public members of a class A general syntax to access public members of a class is as follows // s is object of Student class Student s= new Student(); F Referencing the object’s data: objectRefVar.data e.g., s.name=“Ali”; // accessing public data member F Invoking the object’s method: objectRefVar.methodName(arguments) e.g., s.setName(“Ahmad”); // accessing method s.getName(); // accessing method

15 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Example 1: Defining Classes and Creating Objects Objective: Demonstrate creating objects, accessing data, and using methods. 15 //student class definition class Student { /** name is a data member to store name of a student */ String name ; /** Methods of Student class */ public void setName(String n) { name=n; } public String getName() { return name; } } //Test class Teststudent definition class TestStudent { public static void main (String [] args) { // Creating object Student s = new Student (); s.name=“Ali”; System.out.println(“Name:” + s.name); s.setName(“Ahmad”); System.out.println(“Name:” + s.getName()); }

16 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Second Example: Using the Bicycle Class 16 bike2bike1 ownerName = “ Ben Jones ” ownerName= “ Adam Smith ” Bicycle ownerName getOwnerName ( ) setOwnerName(String ) Data member Methods CLASS OBJECTS

17 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Example 2: Defining Classes and Creating Objects Objective: Demonstrate creating objects, accessing data, and using methods. 17 class Bicycle { // Data Member private String ownerName; //Returns name of this bicycle's owner public String getOwnerName( ) { return ownerName; } //Assigns name of this bicycle's owner public void setOwnerName(String name) { ownerName = name; } class BicycleRegistration { public static void main(String[] args) { Bicycle bike1, bike2; String owner1, owner2; bike1 = new Bicycle( ); //Create and assign values to bike1 bike1.setOwnerName("Adam Smith"); bike2 = new Bicycle( ); //Create and assign values to bike2 bike2.setOwnerName("Ben Jones"); owner1 = bike1.getOwnerName( ); //Output the information owner2 = bike2.getOwnerName( ); System.out.println(owner1 + " owns a bicycle."); System.out.println(owner2 + " also owns a bicycle."); }

18 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Constructors 18 The constructor method is like a normal public method except that it shares the same name as the class and it has no return value not even void since constructors never return a value. It can have none, one or many parameters. Constructors are a special kind of methods that are invoked to construct objects. Normally for a constructor method to be useful we would design it so that it expects parameters. The values passed through these parameters can be used to set the values of the private fields.

19 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Constructors, cont. 19 A constructor with no parameters is referred to as a no-arg constructor. Point to be noted about constructor. 1.Constructors must have the same name as the class itself. 2.Constructors do not have a return type—not even void. 3.Constructors are invoked (called) using the new operator when an object is created. 4.Constructors play the role of initializing objects.

20 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Default Constructor 20 A class may be declared without constructors. In this case, a no-arg constructor with an empty body is implicitly declared in the class. This constructor, called a default constructor, is provided automatically only if no constructors are explicitly declared in the class.

21 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 21 class Account { private String ownerName; private double balance; public Account( ) { ownerName = "Unassigned"; balance = 0.0; } public void add(double amt) { balance = balance + amt; } public void deduct(double amt) { balance = balance - amt; } public void setBalance (double bal) { balance = bal; } public void setOwnerName (String name) { ownerName = name; } public double getBalance( ) { return balance; } public String getOwnerName( ) { return ownerName; } Example 3: Defining Classes with constructors and Creating Objects. class TestAccount{ /* This sample program uses both the Bicycle and Account classes */ public static void main(String[] args) { Account acct; String myName = "Jon Java"; acct = new Account( ); acct.setOwnerName(myName); acct.setBalance(250.00); acct.add(25.00); acct.deduct(50); //Output some information System.out.println("has $ " + acct.getBalance() + " left in the bank"); }

22 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 22 Trace Code

23 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Trace Code 23 Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; Declare myCircle no value myCircle animation Another Example

24 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Trace Code, cont. 24 Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; no value myCircle Create a circle animation

25 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Trace Code, cont. 25 Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; reference value myCircle Assign object reference to myCircle animation

26 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Trace Code, cont. 26 Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; reference value myCircle no value yourCircle Declare yourCircle animation

27 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Trace Code, cont. 27 Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; reference value myCircle no value yourCircle Create a new Circle object animation

28 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Trace Code, cont. 28 Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; reference value myCircle reference value yourCircle Assign object reference to yourCircle animation

29 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Trace Code, cont. 29 Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; reference value myCircle reference value yourCircle Change radius in yourCircle animation

30 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Caution Recall that you use Math.methodName(arguments) (e.g., Math.pow(3, 2.5)) to invoke a method in the Math class. Can you invoke getArea() using Circle1.getArea()? The answer is no. All the methods used before this chapter are static methods, which are defined using the static keyword. However, getArea() is non-static. It must be invoked from an object using objectRefVar.methodName(arguments) (e.g., myCircle.getArea()). More explanations will be given in the section on “Static Variables, Constants, and Methods.” 30

31 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Reference Data Fields The data fields can be of reference types. For example, the following Student class contains a data field name of the String type. 31 public class Student { String name; // name has default value null int age; // age has default value 0 boolean isScienceMajor; // isScienceMajor has default value false char gender; // c has default value '\u0000' }

32 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 The null Value If a data field of a reference type does not reference any object, the data field holds a special literal value, null. 32

33 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Default Value for a Data Field The default value of a data field is null for a reference type, 0 for a numeric type, false for a boolean type, and '\u0000' for a char type. However, Java assigns no default value to a local variable inside a method. 33 public class Test { public static void main(String[] args) { Student student = new Student(); System.out.println("name? " + student.name); System.out.println("age? " + student.age); System.out.println("isScienceMajor? " + student.isScienceMajor); System.out.println("gender? " + student.gender); }

34 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Example public class Test { public static void main(String[] args) { int x; // x has no default value String y; // y has no default value System.out.println("x is " + x); System.out.println("y is " + y); } 34 Compilation error: variables not initialized Java assigns no default value to a local variable inside a method.

35 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Differences between Variables of Primitive Data Types and Object Types 35

36 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Copying Variables of Primitive Data Types and Object Types 36

37 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Garbage Collection As shown in the previous figure, after the assignment statement c1 = c2, c1 points to the same object referenced by c2. The object previously referenced by c1 is no longer referenced. This object is known as garbage. Garbage is automatically collected by JVM. 37

38 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Garbage Collection, cont TIP: If you know that an object is no longer needed, you can explicitly assign null to a reference variable for the object. The JVM will automatically collect the space if the object is not referenced by any variable. 38

39 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 The Date Class Java provides a system-independent encapsulation of date and time in the java.util.Date class. You can use the Date class to create an instance for the current date and time and use its toString method to return the date and time as a string. 39

40 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 The Date Class Example For example, the following code java.util.Date date = new java.util.Date(); System.out.println(date.toString()); displays a string like Sun Mar 09 13:50:19 EST 2003. 40

41 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 The Random Class You have used Math.random() to obtain a random double value between 0.0 and 1.0 (excluding 1.0). A more useful random number generator is provided in the java.util.Random class. 41

42 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 The Random Class Example If two Random objects have the same seed, they will generate identical sequences of numbers. For example, the following code creates two Random objects with the same seed 3. 42 Random random1 = new Random(3); System.out.print("From random1: "); for (int i = 0; i < 10; i++) System.out.print(random1.nextInt(1000) + " "); Random random2 = new Random(3); System.out.print("\nFrom random2: "); for (int i = 0; i < 10; i++) System.out.print(random2.nextInt(1000) + " "); From random1: 734 660 210 581 128 202 549 564 459 961 From random2: 734 660 210 581 128 202 549 564 459 961

43 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Displaying GUI Components When you develop programs to create graphical user interfaces, you will use Java classes such as JFrame, JButton, JRadioButton, JComboBox, and JList to create frames, buttons, radio buttons, combo boxes, lists, and so on. Here is an example that creates two windows using the JFrame class. 43

44 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 44 // Generate frame using standard class JFrame import javax.swing.JFrame; public class TestFrame { public static void main(String[] args) { JFrame frame1 = new JFrame(); frame1.setTitle("Window 1"); frame1.setSize(200, 150); frame1.setLocation(200, 100); frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame1.setVisible(true); JFrame frame2 = new JFrame(); frame2.setTitle("Window 2"); frame2.setSize(200, 150); frame2.setLocation(410, 100); frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame2.setVisible(true); } }

45 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Trace Code 45 JFrame frame1 = new JFrame(); frame1.setTitle("Window 1"); frame1.setSize(200, 150); frame1.setVisible(true); JFrame frame2 = new JFrame(); frame2.setTitle("Window 2"); frame2.setSize(200, 150); frame2.setVisible(true); Declare, create, and assign in one statement reference frame1 : JFrame title: width: height: visible: animation

46 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Trace Code 46 JFrame frame1 = new JFrame(); frame1.setTitle("Window 1"); frame1.setSize(200, 150); frame1.setVisible(true); JFrame frame2 = new JFrame(); frame2.setTitle("Window 2"); frame2.setSize(200, 150); frame2.setVisible(true); reference frame1 : JFrame title: "Window 1" width: height: visible: Set title property animation

47 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Trace Code 47 JFrame frame1 = new JFrame(); frame1.setTitle("Window 1"); frame1.setSize(200, 150); frame1.setVisible(true); JFrame frame2 = new JFrame(); frame2.setTitle("Window 2"); frame2.setSize(200, 150); frame2.setVisible(true); reference frame1 : JFrame title: "Window 1" width: 200 height: 150 visible: Set size property animation

48 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Trace Code 48 JFrame frame1 = new JFrame(); frame1.setTitle("Window 1"); frame1.setSize(200, 150); frame1.setVisible(true); JFrame frame2 = new JFrame(); frame2.setTitle("Window 2"); frame2.setSize(200, 150); frame2.setVisible(true); reference frame1 : JFrame title: "Window 1" width: 200 height: 150 visible: true Set visible property animation

49 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Trace Code 49 JFrame frame1 = new JFrame(); frame1.setTitle("Window 1"); frame1.setSize(200, 150); frame1.setVisible(true); JFrame frame2 = new JFrame(); frame2.setTitle("Window 2"); frame2.setSize(200, 150); frame2.setVisible(true); reference frame1 : JFrame title: "Window 1" width: 200 height: 150 visible: true Declare, create, and assign in one statement reference frame2 : JFrame title: width: height: visible: animation

50 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Trace Code 50 JFrame frame1 = new JFrame(); frame1.setTitle("Window 1"); frame1.setSize(200, 150); frame1.setVisible(true); JFrame frame2 = new JFrame(); frame2.setTitle("Window 2"); frame2.setSize(200, 150); frame2.setVisible(true); reference frame1 : JFrame title: "Window 1" width: 200 height: 150 visible: true reference frame2 : JFrame title: "Window 2" width: height: visible: Set title property animation

51 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Trace Code 51 JFrame frame1 = new JFrame(); frame1.setTitle("Window 1"); frame1.setSize(200, 150); frame1.setVisible(true); JFrame frame2 = new JFrame(); frame2.setTitle("Window 2"); frame2.setSize(200, 150); frame2.setVisible(true); reference frame1 : JFrame title: "Window 1" width: 200 height: 150 visible: true reference frame2 : JFrame title: "Window 2" width: 200 height: 150 visible: Set size property animation

52 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Trace Code 52 JFrame frame1 = new JFrame(); frame1.setTitle("Window 1"); frame1.setSize(200, 150); frame1.setVisible(true); JFrame frame2 = new JFrame(); frame2.setTitle("Window 2"); frame2.setSize(200, 150); frame2.setVisible(true); reference frame1 : JFrame title: "Window 1" width: 200 height: 150 visible: true reference frame2 : JFrame title: "Window 2" width: 200 height: 150 visible: true Set visible property animation

53 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Instance Variables, and Methods 53 Instance variables belong to a specific instance. Instance methods are invoked by an instance of the class.

54 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Static Variables, Constants, and Methods 54 Static variables are shared by all the instances of the class. Static methods are not tied to a specific object. Static constants are final variables shared by all the instances of the class.

55 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Static Variables, Constants, and Methods, cont. 55 To declare static variables, constants, and methods, use the static modifier.

56 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Static Variables, Constants, and Methods, cont. 56

57 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Objective: Demonstrate the roles of instance and class variables and their uses. This example adds a class variable numberOfObjects to track the number of Circle objects created. 57 public class Circle2 { double radius; /** The radius of the circle */ static int numberOfObjects = 0; /** No of objects created */ /** Construct a circle with radius 1 */ Circle2() { radius = 1.0; numberOfObjects++; } /** Construct a circle with a specified radius */ Circle2(double newRadius) { radius = newRadius; numberOfObjects++; } /** Return numberOfObjects */ static int getNumberOfObjects() { return numberOfObjects; } /** Return the area of this circle */ double getArea() { return radius * radius * Math.PI; } }

58 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 58 public class TestCircle2 { /** Main method */ public static void main(String[] args) { System.out.println("Before creating objects"); System.out.println("The number of Circle objects is " + Circle2.numberOfObjects); // Create c1 Circle2 c1 = new Circle2(); // Display c1 BEFORE c2 is created System.out.println("\nAfter creating c1"); System.out.println("c1: radius (" + c1.radius + ") and number of Circle objects (" + c1.numberOfObjects + ")"); // Create c2 Circle2 c2 = new Circle2(5); // Modify c1 c1.radius = 9; // Display c1 and c2 AFTER c2 was created System.out.println("\nAfter creating c2 and modifying c1"); System.out.println("c1: radius (" + c1.radius + ") and number of Circle objects (" + c1.numberOfObjects + ")"); System.out.println("c2: radius (" + c2.radius + ") and number of Circle objects (" + c2.numberOfObjects + ")"); } }

59 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Visibility Modifiers and Accessor/Mutator Methods By default, the class, variable, or method can be accessed by any class in the same package. 59  public The class, data, or method is visible to any class in any package.  private The data or methods can be accessed only by the declaring class. The get and set methods are used to read and modify private properties.

60 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 60 Accessibility Example class Service { public int memberOne; private int memberTwo; public void doOne() { … } private void doTwo() { … } … Service obj = new Service(); obj.memberOne = 10; obj.memberTwo = 20; obj.doOne(); obj.doTwo(); … ClientService

61 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Why Data Fields Should Be private? To protect data. To make class easy to maintain. Internal details of a class are declared private and hidden from the clients. This is information hiding. 61

62 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Example of Data Field Encapsulation 62

63 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Passing Objects to Methods 63 F As we can pass int and double values, we can also pass an object to a method. F When we pass an object, we are actually passing the reference (name) of an object –it means a duplicate of an object is NOT created in the called method. F Passing by value for primitive type value (the value is passed to the parameter) F Passing by value for reference type value (the value is the reference to the object)

64 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Passing Objects to a Method 64 Student getName( ) Student( ) getEmail( ) name email setEmail(String) setName(String) LibraryCard getNumberOfBooks( ) LibraryCard( ) chcekOut( int ) owner borrowCnt getOwnerName( ) setOwner( Student ) toString()

65 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Passing a Student Object name “Joan Java” :Student email jj@javauniv”.edu” card2 owner :LibraryCard borrowCnt 0 student Receiving side Memory Allocation 1 2 Passing side student

66 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Passing a Student Object

67 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Passing a Student Object class LibraryCard { private Student owner; public void setOwner(Student st) { owner = st; } LibraryCard card2; card2 = new LibraryCard(); card2.setOwner(student); Passing Side Receiving Side : LibraryCard owner borrowCnt 0 : Student name “Jon Java” email “jj@javauniv.edu” student card2 st 1 1 Argument is passed 1 2 2 Value is assigned to the data member 2 State of Memory

68 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 68 class Student { private String name; private String email; public Student() { name = "Unassigned"; email = "Unassigned"; } public String getEmail( ) { return email; } public String getName( ) { return name; } //Assigns the name of this student public void setName(String studentName) { name = studentName; } //Assigns the email of this student public void setEmail(String address) { email = address; } class LibraryCard { //student owner of this card private Student owner; //number of books borrowed private int borrowCnt; //numOfBooks are checked out public void checkOut(int numOfBooks) { borrowCnt = borrowCnt + numOfBooks; } //Returns the name of the owner of this card public String getOwnerName( ) { return owner.getName( ); } //Returns the number of books borrowed public int getNumberOfBooks( ) { return borrowCnt; } //Sets the owner of this card to student public void setOwner(Student stud) { owner = stud; } //Returns the string representation of this card public String toString( ) { return "Owner Name: " +owner.getName( )+"\n"+ “Email: " + owner.getEmail( ) + "\n" + "Books Borrowed: " + borrowCnt; }

69 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 69 class Librarian { public static void main( String[] args ) { Student stud; stud = new Student( ); stud.setName("Jon Java"); stud.setEmail("jj@javauniv.edu"); LibraryCard card1, card2; card1 = new LibraryCard( ); card1.setOwner(stud); card1.checkOut(3); card2 = new LibraryCard( ); card2.setOwner(stud); //the same student is the owner of the second card, too System.out.println("Card1 Info:"); System.out.println(card1.toString() + "\n"); System.out.println("Card2 Info:"); System.out.println(card2.toString() + "\n"); }

70 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Sharing an Object 70 F We pass the same Student object to card1 and card2 Since we are actually passing a reference to the same object, it results in owner of two LibraryCard objects pointing to the same Student object

71 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Array of Objects In Java, in addition to arrays of primitive data types, we can declare arrays of objects An array of primitive data is a powerful tool, but an array of objects is even more powerful. The use of an array of objects allows us to model the application more cleanly and logically. 71

72 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 72 class Person { private String name; private int age; private char gender; public Person() { name = "Unassigned"; age = -1; gender=‘u’; } // Return Person Age public int getAge( ) { return age; } // Return Person Gender public char getGender( ) { return gender; } //Return Person Name public String getName( ) { return name; } //Assigns the name of Person public void setName(String personName) { name = personName; } //Assigns the age of Person public void setAge(int personAge) { age = personAge; } //Assigns the Gender of Person (M/F) public void setGender(char personGender) { gender = personGender; } public class Test { public static void main (String[] args) { Person latte; latte = new Person( ); latte.setName("Ms. Latte"); latte.setAge(20); latte.setGender('F'); System.out.println("Name: "+ latte.getName()); System.out.println("Age : "+ latte.getAge()); System.out.println("Sex : "+ latte.getGender());}} The Person class supports the set methods and get methods.

73 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 The Person Class We will use Person objects to illustrate the use of an array of objects. Person latte; latte = new Person( ); latte.setName("Ms. Latte"); latte.setAge(20); latte.setGender('F'); System.out.println( "Name: " + latte.getName() ); System.out.println( "Age : " + latte.getAge() ); System.out.println( "Sex : " + latte.getGender() );

74 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Creating an Object Array - 1 Code State of Memory Person[ ] person; person = new Person[20]; person[0] = new Person( ); A A Only the name person is declared, no array is allocated yet. After is executed A A person

75 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 person Creating an Object Array - 2 Code State of Memory Person[ ] person; person = new Person[20]; person[0] = new Person( ); B B Now the array for storing 20 Person objects is created, but the Person objects themselves are not yet created. After is executed B B 0123416171819 person

76 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Creating an Object Array - 3 Code State of Memory Person[ ] person; person = new Person[20]; person[0] = new Person( ); C C One Person object is created and the reference to this object is placed in position 0. 0123416171819 person 0123416171819 person After is executed C C Person : Person o Not Given U

77 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 The Person Class public class Test { public static void main (String[] args) { Person [ ]prsn=new Person [20]; Prsn[0] = new Person( ); Prsn[0].setName("Ms. Latte"); Prsn[0].setAge(20); Prsn[0].setGender('F'); Prsn[1] = new Person( ); Prsn[1].setName("Mr. Khalid"); Prsn[1].setAge(30); Prsn[1].setGender(‘M');. }

78 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display.Chapter 10 - 78 Person Array Processing – Sample 1 Create Person objects and set up the person array. class Test { public static void main (String[] args) { String name, inpStr; intage; chargender; Person [ ]prsn=new Person [20]; for (int i = 0; i < prsn.length; i++) { name = JOptionPane.showInputDialog(null,"Enter name:"); age = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter age:")); inpStr = JOptionPane.showInputDialog(null,"Enter gender:"); gender = inpStr.charAt(0); prsn[i] = new Person( ); prsn[i].setName ( name ); prsn[i].setAge ( age ); prsn[i].setGender( gender ); }


Download ppt "Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Chapter 8 Objects and Classes."

Similar presentations


Ads by Google