Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class.

Similar presentations


Presentation on theme: "1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class."— Presentation transcript:

1 1 Chapter 2 Objects and Classes

2 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class and how to create an object of a class. F To understand the roles of constructors and use constructors to create objects. F To use UML graphical notations to describe classes and objects. F To distinguish between object reference variables and primitive data type variables. F To use classes in the Java library. F To declare private data fields with appropriate get and set methods to make class easy to maintain. F To develop methods with object arguments. F To understand the difference between instance and static variables and methods. F To determine the scope of variables in the context of a class. F To use the keyword this as the reference to the current object that invokes the instance method. F To store and process objects in arrays. F To apply class abstraction to develop software. F To declare inner classes.

3 3 OO Programming Concepts Objects Object-oriented programming (OOP) involves programming using objects. An object represents or an abstraction of some entity in the real world that can be distinctly identified. For example, a student, a desk, a circle, a button, a cow, a car, a loan, and etc. An object may be physical, like a radio, or intangible, like a song. Just as a noun is a person, place, or thing; so is an object

4 4 OO Programming Concepts An object has a unique identity State or characteristics or attributes, and Action or behaviors. Specifically, an object is an entity that consists of: a set of data fields (also known as properties or attributes) with their current values. A set of methods that use or manipulate the data ( the behaviors).

5 5 Objects – Example 1 An object has both a state and behavior. The state defines the object, and the behavior defines what the object does.

6 Objects – Example 2 F A remote control unit is an object. F A remote control object has three attributes: –the current channel, an integer, –the volume level, an integer, and –the current state of the TV, on or off, true or false, F Along with five behaviors or methods: –raise the volume by one unit, –lower the volume by one unit, –increase the channel number by one, –decrease the channel number by one, and –switch the TV on or off.

7 Objects – Example 2 (Cont.) Three different remote objects, each with unique attribute values (data) but all sharing the same methods or behaviors.

8 Objects – Example 2 (Cont.) The remote control unit exemplifies encapsulation. F Encapsulation is defined as the language feature of packaging attributes and behaviors into a single unit. F Data and methods comprise a single entity. F Each remote control object encapsulates data and methods, attributes and behaviors. F An individual remote unit, an object, stores its own attributes – channel number, volume level, power state – and has the functionality to change those attributes.

9 Objects – Example 3 F A rectangle is an object. F The attributes of a rectangle might be length and width, two floating point numbers; the methods compute and return area and perimeter. F Each rectangle has its own set of attributes; all share the same behaviors

10 Three rectangle objects Objects – Example 3 (Cont.)

11 Three String Objects F A character string is an object that encapsulates data and methods. F The string data consists of an ordered sequence of characters and two (of many) methods include a method that returns the number of characters in the String and one that returns the i th character Objects – Example 4

12 12 Classes Class is a template or blueprint, from which objects of the same type are created. 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.

13 13 Unified Modelling Language (UML) Class Diagram

14 14 Classes

15 Classes – Exercise 1 Rectangle Class F A Rectangle class might specify that every Rectangle object consists of two variables of type double: –double length, and –double width, F Every Rectangle object comes equipped with two methods: –double area(), and //returns the area, length x width, –double perimeter(), //returns the perimeter, 2(length + width). F Individual Rectangle objects may differ in dimension but all Rectangle objects share the same methods F Question: Draw a UML class diagram of rectangle class Create a rectangle class

16 16 Constructors Circle() { } Circle(double newRadius) { radius = newRadius; } Constructors are a special kind of methods that are invoked to construct objects.

17 17 Constructors (Cont.) 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. Constructors play the role of initializing objects.

18 18 Creating Objects Using Constructors Syntax: new ClassName(); Example: new Circle(); new Circle(5.0);

19 19 Default Constructor 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.

20 20 Declaring Object Reference Variables To reference an object, assign the object to a reference variable. To declare a reference variable, use the syntax: ClassName objectRefVar; Example: Circle myCircle;

21 21 Declaring/Creating Objects in a Single Step ClassName objectRefVar = new ClassName(); Example: Circle myCircle = new Circle(); Create an object Assign object reference

22 22 Accessing Objects F Data field can be accessed and its methods invoked using the dot operator (.) – known as object member access operator. F Referencing the object’s data: objectRefVar.data e.g., myCircle.radius F Invoking the object’s method: objectRefVar.methodName(arguments) e.g., myCircle.getArea()

23 23 A Simple Circle Class  Objective: Demonstrate creating objects, accessing data, and using methods. TestCircle1 Run

24 24 Trace Code Circle myCircle = new Circle(5.0); SCircle yourCircle = new Circle(); yourCircle.radius = 100; Declare myCircle no value myCircle animation

25 25 Trace Code, cont. Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; no value myCircle Create a circle animation

26 26 Trace Code, cont. Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; reference value myCircle Assign object reference to myCircle animation

27 27 Trace Code, cont. Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; reference value myCircle no value yourCircle Declare yourCircle animation

28 28 Trace Code, cont. 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

29 29 Trace Code, cont. 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

30 30 Trace Code, cont. Circle myCircle = new Circle(5.0); Circle yourCircle = new Circle(); yourCircle.radius = 100; reference value myCircle reference value yourCircle Change radius in yourCircle animation

31 31 1. public class TestCircle1 { 2. public static void main(String[] args) { 3. Circle1 myCircle = new Circle1(5.0); 4. System.out.println(“The area of the circle of radius “ + 5. myCircle.radius + “ is “ + 6. myCircle.getArea()); 7. Circle1 yourCircle = new Circle1(); 8. System.out.println(“The area of the circle of radius “ + 9. yourCircle.radius + “ is “ + 10. yourCircle.getArea()); 11. yourCircle.radius = 100; 12. System.out.println(“The area of the circle of radius “ + 13. yourCircle.radius + “ is “ + 14. yourCircle.getArea()); 15. } 16. }

32 32 17. class Circle1 { 18. double radius; 19. Circle1( ) { 20. radius = 1.0; 21. } 22. Circle1(double newRadius) { 23. radius = newRadius; 24. } 25. double getArea( ) { 26. return radius * radius * radius * 27. Math.PI; 28. } 29. }

33 33 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 Section 2.7, “Static Variables, Constants, and Methods.”

34 34 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. 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' }

35 35 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.

36 36 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. 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); }

37 37 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); } Compilation error: variables not initialized Java assigns no default value to a local variable inside a method.

38 38 1. public class TestCircle1 { 2. public static void main(String[] args) { 3. double localVar; 4. //Circle1 myCircle = new Circle1(5.0); 5. //System.out.println(“The area of the circle of radius “ + 6. myCircle.radius + “ is “ + 7. myCircle.getArea()); 8. Circle1 yourCircle = new Circle1(); 9. System.out.println(“The default value for radius is “ + 10. yourCircle.radius); 11. System.out.println(“Default value for local variable is “ + 12. localVar); 13. // yourCircle.radius = 100; 14. //System.out.println(“The area of the circle of radius “ + 15. yourCircle.radius + “ is “ + 16. yourCircle.getArea()); 17. } 18. }

39 39 17. class Circle1 { 18. double radius; 19. Circle1( ) { 20. // radius = 1.0; 21. } 22. Circle1(double newRadius) { 23. radius = newRadius; 24. } 25. double getArea( ) { 26. return radius * radius * radius * 27. Math.PI; 28. } 29. }

40 40 Differences between Variables of Primitive Data Types and Object Types

41 41 Copying Variables of Primitive Data Types and Object Types

42 42 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. This clean-up process is called garbage collection Garbage is automatically collected by Java Virtual Machine (JVM).

43 43 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.

44 44 Garbage Collection, cont F If an object remains referenced but is no longer used in a program, the garbage collector does not recycle the memory: Square mySquare = new Square (5.0); // a 5.0 x 5.0 square double areaSquare = mySquare.area(); Triangle myTriangle = new Triangle(6.0, 8.0);// right triangle base = 6.0, height = 8.0 double areaTriangle = myTriangle.area(); Circle myCircle = new Circle(4.0); // a circle of radius 4.0 double areaCircle = myCirclearea(); … // code that uses these objects … // more code that does not use the objects created above... F When Square, Triangle and Circle objects are no longer used by the program, if the objects remain referenced, that is, if references mySquare, myTriangle, and myCircle continue to hold the addresses of these obsolete objects, the garbage collector will not reclaim the memory for these three objects. F Such a scenario causes a memory leak.

45 45 Garbage Collection, cont F A memory leak occurs when an application fails to release or recycle memory that is no longer needed. F The memory leak caused by the Square-Triangle-Circle fragment can be easily rectified by adding a few lines of code : Square mySquare = new Square (5.0); // a 5.0 x 5.0 square double areaSquare = mySquare.area(); Triangle myTriangle = new Triangle(6.0, 8.0);// right triangle base = 6.0, height = 8.0 double areaTriangle = myTriangle.area(); Circle myCircle = new Circle(4.0); // a circle of radius 4.0 double areaCircle = myCircle.area() // code that uses these objects … mySquare = null; myTriangle = null; myCircle = null; // more code that does not use the objects created above... F The Java constant null can be assigned to a reference. F A reference with value null refers to no object and holds no address; it is called a void reference.

46 46 Garbage Collection, cont Referenced and unreferenced objects

47 47 Exercise 1 F Develop an Object Oriented program to display the balance of your account after each transaction. The program must has a class named Account with two type of constructors. –A no-arg constructor that creates a default balance with value is 100.00. –A constructor that update the balance based on the specified transaction, which are either withdrawal or deposit. –A method named getBalance() that returns the balance of the account. Use data field balance to hold the current balance of the account. Assign and display no transaction, transaction value is 200.00 and transaction value is –50.00 when you create the objects.

48 48 Exercise 2 F Write an Object Oriented program to display area and perimeter of a rectangle. Design a class named Rectangle to represent the rectangle and the class contains: –Two double data fields named width and height that specify the width and height of the rectangle. The default values are 1 for both width and height –A no-arg constructor that creates a default rectangle. –A constructor that creates a rectangle with the specified width and height. –A method named getArea() that returns the area of this rectangle. –A method named getPerimeter() that returns the perimeter. Assign width 4 and height 40 for the first object and width 3.5 and height 35.9 to the second object.

49 49 Using Classes from the Java Library Example 2.1 declared the Circle1 class and created objects from the class. Often you will use the classes in the Java library to develop programs. You learned to obtain the current time using System.currentTimeMillis() in previous chapter (Primitive Data Types and Operations), “Displaying Current Time.” You used the division and remainder operators to extract current second, minute, and hour.

50 50 The Date Class Java provides a system-independent encapsulation of date and time in the java.util.Date class. Date class can be used to create an instance for the current date and time  To return the date and time as a string its toString method is used.

51 51 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 Mon Jul 20 12:55:57 MYT 2009

52 52 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.

53 53 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. 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

54 54 Instance Variables, and Methods Instance variables belong to a specific instance. There is a separate copy for every object created. Instance methods are invoked by an instance of the class.

55 55 Static Variables, Constants, and Methods Static variables are shared by all the instances of the class. only exists one copy no matter how many objects create For example, to hold the grand total of anything Static methods are not tied to a specific object. Static constants are final variables shared by all the instances of the class.

56 56 Static Variables, Constants, and Methods, cont. To declare static variables, constants, and methods, use the static modifier. Keyword static denote a class variable

57 57 17. class Circle2 { 18. double radius; 19. static int numberOfObjects = 0; // Class variable 20. 21. Circle2( ) { 22. radius = 1.0; 23. numberOfObjects++ ; } 24. 25. Circle2(double newRadius) { 26. radius = newRadius; 27. numberOfObjects++ ; } 28. 29. double getArea( ) { 30. return radius * radius * Math.PI; } 31. 32. static int getNumberOfObjects() { 33. return numberOfObjects ; } 34. }

58 58 Static Variables, Constants, and Methods, cont. Circle2 circle1 = new Circle2(); Circle2 circle2 = new Circle2(5);

59 59 Static Variables, Constants, and Methods, cont. F circle1.numberOfObjects and circle1.getNumberOfobjects() can be replaced with Circle1.numberOfObjects and Circle2.getNumberOfObjects(). F Syntax: ClassName.methodName(arguments) to invoke a static method ClassName.staticVariable. This improves readability because the user can easily recognise the static method and data in the class.

60 60 Static Variables, Constants, and Methods, cont. F Instance variables and methods can only be used from instance method, not from static methods, since static variables and methods belong to the class as a whole and not to particular objects. F Example: static int getNumberOfObjects() { radius = radius * radius; return numberOfObjects; } * wrong because radius is instance variable, not static variable and cannot be used in static method.

61 61 Visibility Modifiers and Accessor/Mutator Methods By default, the class, variable, or method can be accessed by any class in the same package.  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.

62 62 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.

63 63 NOTE 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).

64 64 Why Data Fields Should Be private? To protect data. To make class easy to maintain.

65 65 Why Data Fields Should Be private? F Example: data field radius and numberOfObjects in the Circle2 class can be modified directly (e.g. myCircle.radius = 5). F This is not a good practice: –Data may be tampered. For example, numberOfObjects is to count the number of objects created, but it may be set to an arbitrary value (e.g. Circle2.numberOfObjects = 10). –It makes the class difficult to maintain and vulnerable to bugs.Suppose you want to modify the Circle2 class to ensure that the radius is non-negative after other programs have already used the class. You have to change not only the Circle2 class, but also the programs that use the Circle2 class.

66 66 Why Data Fields Should Be private? F Data field encapsulation: declare the data field as private to prevent direct modification of properties F Provide a get method to return the value of the data field. (getter/accessor) F Provide a set method to enable a private data field to be updated (setter/mutator)

67 67 Example of Data Field Encapsulation Circle3 RunTestCircle3

68 68 17. public class Circle3 { 18. private double radius = 1; 19. private static int numberOfObjects = 0; 20. 21. public Circle3( ) { 22. numberOfObjects++; } 23. 24. public Circle2(double newRadius) { 25. radius = newRadius; 26. numberOfObjects++; } 27. 28. public void setRadius(double newRadius ) { 29. radius = (newRadius >= 0) ? newRadius : 0; } 30. 31. public static int getNumberOfObjects() { 32. return numberOfObjects; } 33. 34. public double getArea() { 35. return radius * radius * Math.PI 36. } 37. }

69 69 Immutable Objects and Classes If the contents of an object cannot be changed once the object is created, the object is called an immutable object and its class is called an immutable class. If you delete the set method in the Circle class in the preceding example, the class would be immutable because radius is private and cannot be changed without a set method. A class with all private data fields and without mutators is not necessarily immutable. For example, the following class Student has all private data fields and no mutators, but it is mutable.

70 70 Example public class Student { private int id; private BirthDate birthDate; public Student(int ssn, int year, int month, int day) { id = ssn; birthDate = new BirthDate(year, month, day); } public int getId() { return id; } public BirthDate getBirthDate() { return birthDate; } } public class BirthDate { private int year; private int month; private int day; public BirthDate(int newYear, int newMonth, int newDay) { year = newYear; month = newMonth; day = newDay; } public void setYear(int newYear) { year = newYear; } } public class Test { public static void main(String[] args) { Student student = new Student(111223333, 1970, 5, 3); BirthDate date = student.getBirthDate(); date.setYear(2010); // Now the student birth year is changed! } }

71 71 What Class is Immutable? For a class to be immutable, it must mark all data fields private and provide no mutator methods and no accessor methods that would return a reference to a mutable data field object.

72 72 Passing Objects to Methods 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) TestPassObject Run

73 73 Passing Objects to Methods, cont.

74 74 Scope of Variables F The scope of instance and static variables is the entire class. They can be declared anywhere inside a class. F The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be initialized explicitly before it can be used. F The exception is when a data field is initialized based on reference to another data field.

75 75 Scope of Variables public class Circle { public double find getArea() { return radius * radius * Math.PI; } private double radius = 1; } public class Foo { private i; private int j = i + 1; }

76 76 Scope of variables class Foo { int x = 0; int y = 0; Foo() { } void p() { int x = 1; System.out.println(“x = “ + x); System.out.println(“y = “ + y); }

77 77 The this Keyword F Is a reference to the calling object F Use this: – to refer to the object that invokes the instance method. – to refer to an instance data field. – to invoke an overloaded constructor of the same class.

78 78 Serving as Proxy to the Calling Object

79 79 Calling Overloaded Constructor

80 80 Array of Objects Circle[] circleArray = new Circle[10]; An array of objects is actually an array of reference variables. So invoking circleArray[1].getArea() involves two levels of referencing as shown in the next figure. circleArray references to the entire array. circleArray[1] references to a Circle object.

81 81 Array of Objects, cont. Circle[] circleArray = new Circle[10];

82 82 Array of Objects, cont. Summarizing the areas of the circles TotalAreaRun

83 83 1. public class TotalArea { 2. public static void main(String[] args) { 3. Circle3[] circleArray; 4. circleArray = createCircleArray(); 5. printCircleArray(circleArray); 6. } 7. 8. public static Circle3[] createCircleArray() { 9. Circle3[] circleArray = new Circle3[10]; 10. for (int I = 0; I < circleArray.length; i++) { 11. circleArray[i] = new Circle3(Math.random() * 100); 12. return circleArray; 13. }

84 84 13. public static printCircleArray(Circle3[] circleArray) { 14. System.out.println (“Radius\t\t\t\t” + “Area”); 15. for (int i = 0; i < circleArray.length; i++) { 16. System.out.println(circleArray[i].getRadius() + “\t\t” + 17. circleArray[i].getArea() + ‘\n’); 18. } 19. System.out.println(“-----------------”); 20. System.out.println(“The total areas of circles is \t” + 21. sum(circleArray); 22. } 23. 24. public static double sum(Circle3[] circleArray) { 25. double sum = 0; 26. for (int i = 0; i < circleArray.length; i++) 27. sum += circleArray[i].getArea(); 28. return sum; 29. }

85 85 Class Abstraction and Encapsulation Class abstraction means to separate class implementation from the use of the class. The creator of the class provides a description of the class and let the user know how the class can be used. The user of the class does not need to know how the class is implemented. The detail of implementation is encapsulated and hidden from the user.

86 86 Example: The Loan Class TestLoanClassRunLoan

87 87 Example: The Course Class TestCourceRunCourse

88 88 Example: The StackOfIntegers Class Run TestStackOfIntegers

89 89 Implementing StackOfIntegers Class StackOfIntegers

90 90 Note to Instructor You can now cover Chapter 8, “Strings and Text I/O,” or Chapter 12, “GUI Basics.”

91 91 Creating Windows Using the JFrame Class F Objective: Demonstrate using classes from the Java library. Use the JFrame class in the javax.swing package to create two frames; use the methods in the JFrame class to set the title, size and location of the frames and to display the frames. TestFrame Run Optional GUI

92 92 Trace Code 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

93 93 Trace Code 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

94 94 Trace Code 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

95 95 Trace Code 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

96 96 Trace Code 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

97 97 Trace Code 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

98 98 Trace Code 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

99 99 Trace Code 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

100 100 Exercise 3 F Write an Object Oriented program that asks a user to enter the distance of a trip in miles, the miles per gallon estimate for the user’s car, and the average cost of a gallon of gas. Calculate and display the number of gallons of gas needed and the estimated cost of the trip.


Download ppt "1 Chapter 2 Objects and Classes. 2 Objectives F To understand objects and classes and use classes to model objects. F To learn how to declare a class."

Similar presentations


Ads by Google