Download presentation
Presentation is loading. Please wait.
Published byMyles Hancock Modified over 8 years ago
1
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. P ART 1: O BJECTS AND C LASSES 1
2
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. M OTIVATIONS 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, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. O BJECTIVES To describe objects and classes, and use classes to model objects (§8.2). To use UML graphical notation to describe classes and objects (§8.2). To demonstrate how to define classes and create 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 the Java library classes Date, Random, and JFrame (§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, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. OO P ROGRAMMING C ONCEPTS 4 Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that can be distinctly identified. For example, a student, a desk, a circle, a button, and even a loan can all be viewed as objects. 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 or actions.
5
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. O BJECTS 5 An object has both a state and behavior. The state defines the object, and the behavior defines what the object does.
6
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. C LASSES 6 Classes are constructs that define objects of the same type. A Java class uses variables to define data fields and methods to define behaviors. Additionally, a class provides a special type of methods, known as constructors, which are invoked to construct objects from the class.
7
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. C LASSES 7
8
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. UML C LASS D IAGRAM 8
9
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. E XAMPLE : C REATING O BJECTS public class TestSimpleCircle { public static void main(String[] args) { // Create a circle with radius 1 SimpleCircle circle1 = new SimpleCircle(); System.out.println( "The area of the circle of radius " + circle1.radius + " is " +circle1.getArea()); // Create a circle with radius 25 SimpleCircle circle2 = new SimpleCircle( 25 ); System.out.println( "The area of the circle of radius " + circle2.radius + " is " + circle2.getArea()); // Create a circle with radius 125 SimpleCircle circle3 = new SimpleCircle( 125 ); System.out.println( "The area of the circle of radius " + circle3.radius + " is " + circle3.getArea()); // Modify circle radius circle2.radius = 100 ; // or circle2.setRadius(100) System.out.println( "The area of the circle of radius " + circle2.radius + " is " + circle2.getArea()); } 9 Instantiation of objects
10
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. E XAMPLE : D EFINING C LASSES // Define the circle class with two constructors class SimpleCircle { double radius; /** Construct a circle with radius 1 */ SimpleCircle() { radius = 1 ; } /** Construct a circle with a specified radius */ SimpleCircle( double newRadius) { radius = newRadius; } /** Return the area of this circle */ double getArea() { return radius * radius * Math.PI; } /** Return the perimeter of this circle */ double getPerimeter() { return 2 * radius * Math.PI; } /** Set a new radius for this circle */ void setRadius( double newRadius) { radius = newRadius; } } 10
11
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. E XAMPLE : D EFINING C LASSES AND C REATING O BJECTS Try to write the code of the following class, and its Test class 11 TV channels:int volumeLevel:int on:boolean TV() turnOff():void turnOn():void setChannel(int ch):void setVolume(int vl):void channelUp():void channelDown():void volumeUp():void volumeDown():void
12
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. C ONSTRUCTORS Circle() { } Circle(double newRadius) { radius = newRadius; } 12 Constructors are a special kind of methods that are invoked to construct objects.
13
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. C ONSTRUCTORS, CONT. 13 A constructor with no parameters is referred to as a no-arg constructor. · Constructors must have the same name as the class itself. · Constructors do not have a return type—not even void. · Constructors are invoked using the new operator when an object is created on memory. Constructors play the role of initializing objects.
14
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. C REATING O BJECTS U SING C ONSTRUCTORS new ClassName(); Example: new Circle(); new Circle(5.0); 14
15
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. D EFAULT C ONSTRUCTOR 15 A class may be defined 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 defined in the class. (Once you defined your own constructors you should only use one of them to create objects – java default const. is no longer available)
16
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. D ECLARING O BJECT R EFERENCE V ARIABLES To reference an object, assign the object to a reference variable. To declare a reference variable, use the syntax: ClassName objectRefVar; Example: Circle myCircle; 16
17
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. D ECLARING /C REATING O BJECTS IN A S INGLE S TEP To create an object (instantiate an object) we use the new constructor stmt. new ClassName Example: new Circle(); This object is called (anonymous) You can not use the object created in the previous stmt unless you referenced the object using a reference variable. ClassName objectRefVar = new ClassName(); Or ClassName objectRefVar; objectRefVar =new ClassName(); Example: Circle myCircle = new Circle(); Or Circle myCircle; myCircle= new Circle(); Note: The object is also called instance because it is an instance of the class created from. 17
18
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. A CCESSING O BJECT ’ S M EMBERS Referencing the object’s data: objectRefVar.data e.g., myCircle.radius Invoking the object’s method: objectRefVar.methodName(arguments) e.g., myCircle.getArea() (take care if the method returns data) 18
19
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. T RACE C ODE 19 Circle myCircle = new Circle(5.0); SCircle yourCircle = new Circle(); yourCircle.radius = 100; Declare myCircle no value myCircle
20
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. T RACE C ODE, CONT. 20 Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; no value myCircle Create a circle
21
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. T RACE C ODE, CONT. 21 Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; reference value myCircle Assign object reference to myCircle
22
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. T RACE C ODE, CONT. 22 Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; reference value myCircle no value yourCircle Declare yourCircle
23
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. T RACE C ODE, CONT. 23 Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; reference value myCircle no value yourCircle Create a new Circle object
24
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. T RACE C ODE, CONT. 24 Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; reference value myCircle reference value yourCircle Assign object reference to yourCircle
25
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. T RACE C ODE, CONT. 25 Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; reference value myCircle reference value yourCircle Change radius in yourCircle
26
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. D ATA F IELDS The data fields can be of reference types. For example, the following Student class contains a data field name of the String type. If a data field of a reference type does not reference any object, the data field holds a special literal value, null. 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. 26
27
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. D EFAULT V ALUE FOR A D ATA F IELD 27 public class Test { public static void main(String[] args) { int x; // no default value from java to local variables 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); System.out.println(“x? " + x); } 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' }
28
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. R EMEMBER … S COPE Scope is the life time of anything you can imagine in your program even the program it self has a scope in which it exists in memory. Scope of variables starts from the instant they are created in memory (declaration statement) until the end of block in which the variable was created in. Ex. for(int i=1; i<5; i++){ … } i is created inside the for block so it does not exist outside the block. Any use to i variable outside for will lead to syntax error. For that reason data fields can be described as global variables they can used in any method inside the class block, where variables declared inside methods are described as local variables they only can be used from inside the method. 28
29
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. D IFFERENCES BETWEEN V ARIABLES OF P RIMITIVE D ATA T YPES AND O BJECT T YPES 29 A) Assigning values: o Primitive type variables contains the value assigned to it o Reference type variables contains a reference (address) to another location in memory which contains data fields values of the created object using new operator. o if no object assigned to a reference variable then null value is assigned.
30
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. D IFFERENCES BETWEEN V ARIABLES OF P RIMITIVE D ATA T YPES AND O BJECT T YPES B) Comparing Variables of Primitive Data Types and Object Types: if (x= =y) compares the contents of x and y true if (c1= =c2) compares the references (addresses) values of c1 and c2 false (they don’t point to the same object) 30 x 2 y 2 c1 Circle: c1 rad: 10 c2 Circle: c2 rad: 10
31
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. D IFFERENCES BETWEEN V ARIABLES OF P RIMITIVE D ATA T YPES AND O BJECT T YPES 31 C) Copying Variables of Primitive Data Types and Object Types Garbage
32
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. G ARBAGE C OLLECTION 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. 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. 32
33
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. EX.EX. Which of the following code segments lead to Garbage? A)Circle c1=new Circle(); Circle c2=c1; B)Circle c1=new Circle(); Circle c2; c1=c2; C)Circle c1=new Circle(); Circle c2=new Circle(); Circle c3=c2; D)new Circle(); 33
34
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. I NSTANCE V ARIABLES, AND M ETHODS 34 Instance variables belong to a specific instance. Instance methods are invoked by an instance of the class.
35
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. S TATIC V ARIABLES, C ONSTANTS, AND M ETHODS 35 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. To declare static variables, constants, and methods, use the static modifier.
36
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. S TATIC V ARIABLES, C ONSTANTS, AND M ETHODS, CONT. 36
37
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. E XAMPLE OF U SING I NSTANCE AND C LASS V ARIABLES AND M ETHOD 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. public class CircleWithStaticMembers { double radius; static int numberOfObjects = 0 ; CircleWithStaticMembers() { radius = 1. 0 ; numberOfObjects++; } CircleWithStaticMembers( double newRadius) { radius = newRadius; numberOfObjects++; } static int getNumberOfObjects() { return numberOfObjects; } double getArea() { return radius * radius * Math.PI; } } 37
38
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. E XAMPLE CONT. public class TestCircleWithStaticMembers { public static void main(String[] args) { System.out.println( "Before creating objects" ); System.out.println( "The number of Circle objects is " + CircleWithStaticMembers.numberOfObjects); CircleWithStaticMembers c1 = new CircleWithStaticMembers(); System.out.println( “After creating c1" ); System.out.println( "c1 radius " + c1.radius + “ and number of Circle objects " + c1.numberOfObjects ); CircleWithStaticMembers c2 = new CircleWithStaticMembers( 5 ); c1.radius = 9 ; System.out.println( “After 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 ); } 38
39
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. V ISIBILITY M ODIFIERS AND A CCESSOR /M UTATOR M ETHODS 39 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. non : By default, the class, variable, or method can be accessed by any class in the same package. This visibility is called non or package private. The get and set methods are used to read and modify private properties.
40
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 40 The private modifier restricts access to within a class, the default modifier restricts access to within a package, and the public modifier enables unrestricted access. Ex. Write down the variables and methods that can be accessed by each class.
41
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. NOTE 41 An object cannot access its private members, as shown in (b). It is OK, however, if the object is declared in its own class, as shown in (a).
42
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. A CCESSOR /M UTATOR M ETHODS If you want to Access any variable or method in a wider range you have to use a mutator/ accessor methods with stronger accessing privilege. For example if you want to access a private variable from outside the class you have to add a set method to change private variables values and a get method to return private variables values. class A{ private int x; void setX( int newX ){ x=newX; } int getX( ){ return x; } } In this case x can be accessed through set and get methods from classes in the same package if you would like to access it from all packages you have to declare set and get methods as public 42 class TestA{ public static void main(String arg[]){ A a1=new A(); a1.setX(2); System.out.print(a1.getX()); }
43
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. W HY D ATA F IELDS S HOULD B E PRIVATE ? To protect data. To make class easy to maintain. 43
44
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. E XAMPLE OF D ATA F IELD E NCAPSULATION 44
45
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. E XAMPLE CONT. public class CircleWithPrivateDataFields { private double radius = 1 ; private static int numberOfObjects = 0 ; public CircleWithPrivateDataFields() { numberOfObjects++; } public CircleWithPrivateDataFields( double newRadius) { radius = newRadius; numberOfObjects++; } public double getRadius() { return radius; } public void setRadius( double newRadius) { radius = (newRadius >= 0 ) ? newRadius : 0 ; } public static int getNumberOfObjects() { return numberOfObjects; } public double getArea() { return radius * radius * Math.PI; } } 45
46
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. E X CONT. public class TestCircleWithPrivateDataFields { public static void main(String[] args){ CircleWithPrivateDataFields myCircle = new CircleWithPrivateDataFields( 5. 0 ); System.out.println( "The area of the circle of radius " + myCircle.getRadius() + " is " + myCircle.getArea()); myCircle.setRadius(myCircle.getRadius() * 1. 1 ); System.out.println( "The area of the circle of radius " + myCircle.getRadius() + " is " + myCircle.getArea()); } 46
47
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. D ISPLAYING GUI C OMPONENTS 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. 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 ); } 47
48
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. T RACE C ODE 48 JFrame frame1 = new JFrame(); frame1.setTitle("Window 1"); frame1.setSize(200, 150); frame1.setVisible(true); Declare, create, and assign in one statement reference frame1 : JFrame title: width: height: visible:
49
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. T RACE C ODE 49 JFrame frame1 = new JFrame(); frame1.setTitle("Window 1"); frame1.setSize(200, 150); frame1.setVisible(true); reference frame1 : JFrame title: "Window 1" width: height: visible: Set title property
50
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. T RACE C ODE 50 JFrame frame1 = new JFrame(); frame1.setTitle("Window 1"); frame1.setSize(200, 150); frame1.setVisible(true); reference frame1 : JFrame title: "Window 1" width: 200 height: 150 visible: Set size property
51
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. T RACE C ODE 51 JFrame frame1 = new JFrame(); frame1.setTitle("Window 1"); frame1.setSize(200, 150); frame1.setVisible(true); reference frame1 : JFrame title: "Window 1" width: 200 height: 150 visible: true Set visible property
52
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. A DDING GUI C OMPONENTS TO W INDOW You can add graphical user interface components, such as buttons, labels, text fields, combo boxes, lists, and menus, to the window. The components are defined using classes. Here is an example to create buttons, labels, text fields, check boxes, radio buttons, and combo boxes. HW: Write a program that displays on screen buttons, labels, text fields, check boxes, radio buttons and combo boxes. 52
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.