Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Size: px
Start display at page:

Download "Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved."

Transcription

1 Chapter 8 Objects and Classes Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk 1

2 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 Objectives 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 primitivetype arguments and object-type arguments ( 8.10). To store and process objects in arrays ( 8.11). 3

4 OO Programming Concepts 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. 4

5 Objects Class Name: Circle A class template Data Fields: radius is Methods: getarea Circle Object 1 Circle Object 2 Circle Object 3 Data Fields: radius is 10 Data Fields: radius is 25 Data Fields: radius is 125 Three objects of the Circle class An object has both a state and behavior. The state defines the object, and the behavior defines what the object does. 5

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

7 Classes class Circle { /** The radius of this circle */ double radius = 1.0; /** Construct a circle object */ Circle() { } /** Construct a circle object */ Circle(double newradius) { radius = newradius; } Data field Constructors } /** Return the area of this circle */ double getarea() { return radius * radius * ; } Method 7

8 UML Class Diagram UML Class Diagram Circle Class name radius: double Data fields Circle() Circle(newRadius: double) Constructors and methods getarea(): double circle1: Circle radius = 1.0 circle2: Circle radius = 25 circle3: Circle radius = 125 UML notation for objects 8

9 Two examples for Defining Classes and Creating Objects Objective: Demonstrate creating objects, accessing data, and using methods. 9

10 Example1(TestSimpleCircle.java): 1 public class TestSimpleCircle { 2 /** Main method */ 3 public static void main(string[] args) { 4 // Create a circle with radius 1 5 SimpleCircle circle1 = new SimpleCircle(); 6 System.out.println("The area of the circle of radius + circle1.radius + " is " + circle1.getarea()); 7 8 // Create a circle with radius 25 9 SimpleCircle circle2 = new SimpleCircle(25); 10 System.out.println("The area of the circle of radius " + circle2.radius + " is " + circle2.getarea()); // Create a circle with radius SimpleCircle circle3 = new SimpleCircle(125); 14 System.out.println("The area of the circle of radius " + circle3.radius + " is " + circle3.getarea()); // Modify circle radius 17 circle2.radius = 100; // or circle2.setradius(100) 18 System.out.println("The area of the circle of radius + circle2.radius + " is " + circle2.getarea()); 19 } 20 } 10

11 Example1(TestSimpleCircle.java), cont: 21 // Define the circle class with two constructors 22 class SimpleCircle { 23 double radius; /** Construct a circle with radius 1 */ 26 SimpleCircle() { radius = 1; } /** Construct a circle with a specified radius */ 29 SimpleCircle(double newradius) { radius = newradius; } /** Return the area of this circle */ 32 double getarea() { return radius * radius * Math.PI; } /** Return the perimeter of this circle */ 35 double getperimeter() { return 2 * radius * Math.PI; } /** Set a new radius for this circle */ 38 void setradius(double newradius) { radius = newradius; } 39 } 11

12 Example2(TV.java): 1 public class TV { 2 int channel = 1; // Default channel is 1 3 int volumelevel = 1; // Default volume level is 1 4 boolean on = false; // By default TV is off 5 public TV() { } 6 public void turnon() { on = true; } 7 public void turnoff() { on = false; } 8 9 public void setchannel(int newchannel) { 10 if (on && newchannel >= 1 && newchannel <= 120) 11 channel = newchannel; } public void setvolume(int newvolumelevel) { 14 if (on && newvolumelevel >= 1 && newvolumelevel <= 7) 15 volumelevel = newvolumelevel; } public void channelup() { if (on && channel < 120) channel++; } public void channeldown() { if (on && channel > 1) channel--; } public void volumeup() { if (on && volumelevel < 7) volumelevel++; } public void volumedown() { if (on && volumelevel > 1) volumelevel--; } 24 } 12

13 Example2(TestTV.java),cont : 1 public class TestTV { 2 public static void main(string[] args) { 3 TV tv1 = new TV(); 4 tv1.turnon(); 5 tv1.setchannel(30); 6 tv1.setvolume(3); 7 8 TV tv2 = new TV(); 9 tv2.turnon(); 10 tv2.channelup(); 11 tv2.channelup(); 12 tv2.volumeup(); System.out.println("tv1's channel is " + tv1.channel 15 + " and volume level is " + tv1.volumelevel); 16 System.out.println("tv2's channel is " + tv2.channel 17 + " and volume level is " + tv2.volumelevel); 18 } 19 } 13

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

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

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

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

18 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; 18

19 Declaring/Creating Objects in a Single Step ClassName objectrefvar = new ClassName(); Example: Assign object reference Create an object Circle mycircle = new Circle(); 19

20 Accessing Object s Members Referencing the object s data: objectrefvar.data e.g., mycircle.radius Invoking the object s method: objectrefvar.methodname(arguments) e.g., mycircle.getarea() 20

21 (1) Circle mycircle = new Circle(5.0); (2) Circle yourcircle = new Circle(); (3) yourcircle.radius = 100; Trace Code mycircle reference value yourcircle reference value yourcircle reference value : Circle : Circle : Circle radius: 5.0 radius: 1.0 radius: (1) (2) (3) 21

22 Recall that you use Caution Math.methodName(arguments) (arguments)(e.g.,(e.g., Math.pow(3, 2.5)) to invoke a method in the Mathclass. 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 statickeyword. However, getarea()is non-static. It must be invoked from an object using objectrefvar.methodname(arguments) (arguments)(e.g.,(e.g., mycircle.getarea() ()).). More explanations will be given in the section on Static Variables, Constants, and Methods. 22

23 Reference Data Fields The data fields can be of reference types. For example, the following Studentclass contains a data field nameof 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' 23

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

25 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); 25

26 Example Java assigns no default value to a local variable inside a method. 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 26

27 Differences between Variables of Primitive Data Types and Object Types Primitive type int i = 1 i 1 Created using new Circle() Object type Circle c c reference c: Circle radius = 1 27

28 Copying Variables of Primitive Data Types and Object Types Primitive type assignment i = j Before: After: i 1 i 2 j 2 j 2 c1 Before: Object type assignment c1 = c2 After: c1 c2 c2 c1: Circle radius = 5 C2: Circle radius = 9 c1: Circle radius = 5 C2: Circle radius = 9 28

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

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

31 The Date Class Java provides a system-independent encapsulation of date and time in the java.util.dateclass. You can use the Dateclass to create an instance for the current date and time and use its tostringmethod to return the date and time as a string. The + sign indicates public modifer java.util.date +Date() +Date(elapseTime: long) +tostring(): String +gettime(): long +settime(elapsetime: long): void Constructs a Date object for the current time. Constructs a Date object for a given time in milliseconds elapsed since January 1, 1970, GMT. Returns a string representing the date and time. Returns the number of milliseconds since January 1, 1970, GMT. Sets a new elapse time in the object. 31

32 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 likesun Mar 09 13:50:19 EST

33 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.randomclass. java.util.random +Random() +Random(seed: long) +nextint(): int +nextint(n: int): int +nextlong(): long +nextdouble(): double +nextfloat(): float +nextboolean(): boolean Constructs a Random object with the current time as its seed. Constructs a Random object with a specified seed. Returns a random int value. Returns a random int value between 0 and n (exclusive). Returns a random long value. Returns a random double value between 0.0 and 1.0 (exclusive). Returns a random float value between 0.0F and 1.0F (exclusive). Returns a random boolean value. 33

34 The Random Class Example If two Randomobjects have the same seed, they will generate identical sequences of numbers. For example, the following code creates two Randomobjects 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(.nextInt(1000) + " "); Random random2 = new Random(3); System.out.print(" ("\nfrom random2: "); for (int i = 0; i < 10; i++) System.out.print(random2.nextInt(.nextInt(1000) + " "); From random1: From random2:

35 Displaying GUI Components When you develop programs to create graphical user interfaces, you will use Java classes such as JFrame, JButton, JRadioButton, JComboBox, and JListto create frames, buttons, radio buttons, combo boxes, lists, and so on. The next slide has an example that creates two windows using the JFrame class. 35

36 Example(TestFrame.java): 1 import javax.swing.jframe; 2 3 public class TestFrame { 4 public static void main(string[] args) { 5 JFrame frame1 = new JFrame(); 6 frame1.settitle("window 1"); 7 frame1.setsize(200, 150); 8 frame1.setlocation(200, 100); 9 frame1.setdefaultcloseoperation(jframe.exit_on_close); 10 frame1.setvisible(true); JFrame frame2 = new JFrame(); 13 frame2.settitle("window 2"); 14 frame2.setsize(200, 150); 15 frame2.setlocation(410, 100); 16 frame2.setdefaultcloseoperation(jframe.exit_on_close); 17 frame2.setvisible(true); 18 } 19 } 36

37 JFrame frame1 = new JFrame(); frame1.settitle("window 1"); frame1.setsize(.setsize(200, 150); frame1.setlocation(.setlocation(200, 100); frame1.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE); frame1.setvisible(.setvisible(true); Trace Code frame1 reference : JFrame title: "Window 1" width: 200 height: 150 x:200 y:100 visible: true JFrame frame2 = new JFrame(); frame2.settitle("window 2"); frame2.setsize(.setsize(200, 150); frame2.setlocation(.setlocation(410, 100); frame2.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE); frame2.setvisible(.setvisible(true); 37 frame2 reference : JFrame title: "Window 2" width: 200 height: 150 x:410 y:100 visible: true

38 Adding GUI Components to Window 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. The next two slides have an example to create buttons, labels, text fields, check boxes, radio buttons, and combo boxes. 38

39 Example(GUIComponents.java): 1 import javax.swing.*; 2 public class GUIComponents { 3 public static void main(string[] args) { 4 // Create a button with text OK 5 JButton jbtok = new JButton("OK"); 6 // Create a button with text Cancel 7 JButton jbtcancel = new JButton("Cancel"); 8 // Create a label with text "Enter your name: " 9 JLabel jlblname = new JLabel("Enter your name: "); 10 // Create a text field with text "Type Name Here" 11 JTextField jtfname = new JTextField("Type Name Here"); 12 // Create a check box with text bold 13 JCheckBox jchkbold = new JCheckBox("Bold"); 14 // Create a check box with text italic 15 JCheckBox jchkitalic = new JCheckBox("Italic"); 16 // Create a radio button with text red 17 JRadioButton jrbred = new JRadioButton("Red"); 18 // Create a radio button with text yellow 19 JRadioButton jrbyellow = new JRadioButton("Yellow"); 20 // Create a combo box with several choices 21 JComboBox jcbocolor = new JComboBox(new String[]{"Freshman", 22 "Sophomore", "Junior", "Senior"}); 23 39

40 Example(GUIComponents.java), cont. : 24 // Create a panel to group components 25 JPanel panel = new JPanel(); 26 panel.add(jbtok); // Add the OK button to the panel 27 panel.add(jbtcancel); // Add the Cancel button to the panel 28 panel.add(jlblname); // Add the label to the panel 29 panel.add(jtfname); // Add the text field to the panel 30 panel.add(jchkbold); // Add the check box to the panel 31 panel.add(jchkitalic); // Add the check box to the panel 32 panel.add(jrbred); // Add the radio button to the panel 33 panel.add(jrbyellow); // Add the radio button to the panel 34 panel.add(jcbocolor); // Add the combo box to the panel JFrame frame = new JFrame(); // Create a frame 37 frame.add(panel); // Add the panel to the frame 38 frame.settitle("show GUI Components"); 39 frame.setsize(450, 100); 40 frame.setlocation(200, 100); 41 frame.setdefaultcloseoperation(jframe.exit_on_close); 42 frame.setvisible(true); 43 } 44 } 40

41 Instance Variables, and Methods Instance variables belong to a specific instance. Instance methods are invoked by an instance of the class. 41

42 Static Variables, Constants, and Methods 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. 42

43 Static Variables, Constants, and Methods, cont. To declare static variables, constants, and methods, use the static modifier. 43

44 Static Variables, Constants, and Methods, cont. instantiate circle1 Memory Circle radius: double numberofobjects: int getnumberofobjects(): int +getarea(): double instantiate radius = 1 numberofobjects = 2 circle2 1 radius 2 numberofobjects After two Circle objects were created, numberofobjects is 2. UML Notation: +: public variables or methods underline: static variables or methods radius = 5 numberofobjects = 2 5 radius 44

45 Example of Using Instance and Class Variables and Method Objective: Demonstrate the roles of instance and class variables and their uses. The next two slides have an example adds a class variable numberofobjects to track the number of Circle objects created. 45

46 Example(CircleWithStaticMembers.java): 1 public class CircleWithStaticMembers { 2 /** The radius of the circle */ 3 double radius; 4 /** The number of the objects created */ 5 static int numberofobjects = 0; 6 /** Construct a circle with radius 1 */ 7 CircleWithStaticMembers() { 8 radius = 1.0; 9 numberofobjects++; 10 } 11 /** Construct a circle with a specified radius */ 12 CircleWithStaticMembers(double newradius) { 13 radius = newradius; 14 numberofobjects++; 15 } 16 /** Return numberofobjects */ 17 static int getnumberofobjects() { 18 return numberofobjects; 19 } 20 /** Return the area of this circle */ 21 double getarea() { 22 return radius * radius * Math.PI; 23 } 24 } 46

47 Example(TestCircleWithStaticMembers.java): 1 public class TestCircleWithStaticMembers { 2 /** Main method */ 3 public static void main(string[] args) { 4 System.out.println("Before creating objects"); 5 System.out.println("The number of Circle objects is " + CircleWithStaticMembers.numberOfObjects); 6 // Create c1 7 CircleWithStaticMembers c1 = new CircleWithStaticMembers(); 8 // Display c1 BEFORE c2 is created 9 System.out.println("\nAfter creating c1"); 10 System.out.println("c1: radius (" + c1.radius + ") and number of Circle objects (" + 11 c1.numberofobjects + ")"); 12 // Create c2 13 CircleWithStaticMembers c2 = new CircleWithStaticMembers(5); 14 // Modify c1 15 c1.radius = 9; 16 // Display c1 and c2 AFTER c2 was created 17 System.out.println("\nAfter creating c2 and modifying c1"); 18 System.out.println("c1: radius (" + c1.radius + ") and number of Circle objects (" + 19 c1.numberofobjects + ")"); 20 System.out.println("c2: radius (" + c2.radius + ") and number of Circle objects (" + 21 c2.numberofobjects + ")"); 22 } 23 } 47

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

49 package p1; package p2; public class C1 { public int x; int y; private int z; } public void m1() { } void m2() { } private void m3() { } public class C2 { void amethod() { C1 o = new C1(); can access o.x; can access o.y; cannot access o.z; } } can invoke o.m1(); can invoke o.m2(); cannot invoke o.m3(); public class C3 { void amethod() { C1 o = new C1(); can access o.x; cannot access o.y; cannot access o.z; } } can invoke o.m1(); cannot invoke o.m2(); cannot invoke o.m3(); package p1; package p2; class C1 {... } public class C2 { can access C1 } public class C3 { cannot access C1; can access C2; } 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. 49

50 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). public class F { public class Test { private boolean x; public static void main(string[] args) { F f = new F (); System.out.println(f.x); System.out.println(f.convert()); } } public static void main(string[] args) { Foo f = new F(); System.out.println(f.x); System.out.println(f.convert(f.x)); } } private int convert(boolean b) { return x? 1 : -1; } (a) This is OK because object f is used inside the F class (b) This is wrong because x and convert are private in F. 50

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

52 Example of Data Field Encapsulation The - sign indicates private modifier -radius: double Circle -numberofobjects: int The radius of this circle (default: 1.0). The number of circle objects created. +Circle() +Circle(radius: double) +getradius(): double +setradius(radius: double): void +getnumberofobject(): int +getarea(): double Constructs a default circle object. Constructs a circle object with the specified radius. Returns the radius of this circle. Sets a new radius for this circle. Returns the number of circle objects created. Returns the area of this circle. 52

53 Example(CircleWithPrivateDataFields.java): 1 public class CircleWithPrivateDataFields { 2 /** The radius of the circle */ 3 private double radius = 1; 5 /** The number of the objects created */ 6 private static int numberofobjects = 0; 8 /** Construct a circle with radius 1 */ 9 public CircleWithPrivateDataFields( ) { numberofobjects++; } 13 /** Construct a circle with a specified radius */ 14 public CircleWithPrivateDataFields(double newradius) { 15 radius = newradius; 16 numberofobjects++; 17 } 19 /** Return radius */ 20 public double getradius( ) { return radius; } 24 /** Set a new radius */ 25 public void setradius(double newradius) { radius = (newradius >= 0)? newradius : 0; } 29 /** Return numberofobjects */ 30 public static int getnumberofobjects( ) { return numberofobjects; } 34 /** Return the area of this circle */ 35 public double getarea() { return radius * radius * Math.PI; } 38 } 53

54 Example(TestCircleWithPrivateDataFields.java): 1 public class TestCircleWithPrivateDataFields { 2 /** Main method */ 3 public static void main(string[] args) { 4 // Create a Circle with radius CircleWithPrivateDataFields mycircle = new CircleWithPrivateDataFields(5.0); 6 System.out.println("The area of the circle of radius " + mycircle.getradius() + 7 " is " + mycircle.getarea()); 8 // Increase mycircle's radius by 10% 9 mycircle.setradius(mycircle.getradius() * 1.1); 10 System.out.println("The area of the circle of radius " + mycircle.getradius() + 11" is " + mycircle.getarea()); 12 } 13 } 54

55 Passing Objects to Methods Passing by value for primitive type value (the value is passed to the parameter) Passing by value for reference type value (the value is the reference to the object) 55

56 Example(TestPassObject.java): 1 public class TestPassObject { 2 /** Main method */ 3 public static void main(string[] args) { 4 // Create a Circle object with radius 1 5 CircleWithPrivateDataFields mycircle = new CircleWithPrivateDataFields(1); 7 8 // Print areas for radius 1, 2, 3, 4, and 5. 9 int n = 5; 10 printareas(mycircle, n); // See mycircle.radius and times 13 System.out.println("\n" + "Radius is " + mycircle.getradius()); 14 System.out.println("n is " + n); 15 } /** Print a table of areas for radius */ 18 public static void printareas( CircleWithPrivateDataFields c, int times) { 20 System.out.println("Radius \t\tarea"); 21 while (times >= 1) { 22 System.out.println(c.getRadius() + "\t\t" + c.getarea()); 23 c.setradius(c.getradius() + 1); 24 times--; 25 } 26 } } 56

57 Passing Objects to Methods, cont. Stack Space required for the printareas method int times: 5 Circle c: reference Space required for the main method int n: 5 mycircle: reference Pass by value (here the value is 5) Pass by value (here the value is the reference for the object) Heap A circle object 57

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

59 Array of Objects, cont. Circle[] circlearray = new Circle[10]; circlearray reference circlearray[0] Circle object 0 circlearray[1] Circle object 1 circlearray[9] Circle object 9 59

60 Array of Objects, cont. Example of the areas of the circles 60

61 Example(TotalArea.java): 1 public class TotalArea { 2 /** Main method */ 3 public static void main(string[] args) { 4 // Declare circlearray 5 CircleWithPrivateDataFields[] circlearray; 6 7 // Create circlearray 8 circlearray = createcirclearray(); 9 10 // Print circlearray and total areas of the circles 11 printcirclearray(circlearray); 12 } /** Create an array of Circle objects */ 15 public static CircleWithPrivateDataFields[] createcirclearray() { 16 CircleWithPrivateDataFields[] circlearray = 17 new CircleWithPrivateDataFields[5]; for (int i = 0; i < circlearray.length; i++) { 20 circlearray[i] = 21 new CircleWithPrivateDataFields(Math.random() * 100); 22 } // Return Circle array 25 return circlearray; 26 } 27 61

62 Example(TotalArea.java), cont. : 28 /** Print an array of circles and their total area */ 29 public static void printcirclearray( 30 CircleWithPrivateDataFields[] circlearray) { 31 System.out.printf("%-30s%-15s\n", "Radius", "Area"); 32 for (int i = 0; i < circlearray.length; i++) { 33 System.out.printf("%-30f%-15f\n", circlearray[i].getradius(), 34 circlearray[i].getarea()); 35 } System.out.println(" "); // Compute and display the result 40 System.out.printf("%-30s%-15f\n", "The total areas of circles is", 41 sum(circlearray)); 42 } /** Add circle areas */ 45 public static double sum( 46 CircleWithPrivateDataFields[] circlearray) { 47 // Initialize sum 48 double sum = 0; // Add areas to sum 51 for (int i = 0; i < circlearray.length; i++) 52 sum += circlearray[i].getarea(); return sum; 55 } } 62

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

Chapter 8 Objects and Classes. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. Chapter 8 Objects and Classes 1 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections, loops, methods, and arrays. However, these Java

More information

OO Programming Concepts

OO Programming Concepts Chapter 8 Objects and Classes 1 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections, loops, methods, and arrays. However, these Java

More information

Chapter 9 Objects and Classes. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved.

Chapter 9 Objects and Classes. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved. Chapter 9 Objects and Classes 1 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections, loops, methods, and arrays. However, these Java

More information

Chapter 8 Objects and Classes Part 1

Chapter 8 Objects and Classes Part 1 Chapter 8 Objects and Classes Part 1 1 OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that can be distinctly

More information

Chapter 9 Objects and Classes. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.

Chapter 9 Objects and Classes. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Chapter 9 Objects and Classes rights reserved. 1 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections, loops, methods, and arrays. However,

More information

Chapter 8 Objects and Classes

Chapter 8 Objects and Classes Chapter 8 Objects and Classes 1 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections, loops, methods, and arrays. However, these Java

More information

Chapter 9 Objects and Classes. OO Programming Concepts. Classes. Objects. Motivations. Objectives. CS1: Java Programming Colorado State University

Chapter 9 Objects and Classes. OO Programming Concepts. Classes. Objects. Motivations. Objectives. CS1: Java Programming Colorado State University Chapter 9 Objects and Classes CS1: Java Programming Colorado State University Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections, loops,

More information

Chapter 9. Objects and Classes

Chapter 9. Objects and Classes Chapter 9 Objects and Classes 1 OO Programming in Java Other than primitive data types (byte, short, int, long, float, double, char, boolean), everything else in Java is of type object. Objects we already

More information

UFCE3T-15-M Object-oriented Design and Programming

UFCE3T-15-M Object-oriented Design and Programming UFCE3T-15-M Object-oriented Design and Programming Block1: Objects and Classes Jin Sa 27-Sep-05 UFCE3T-15-M Programming part 1 Objectives To understand objects and classes and use classes to model objects.

More information

OO Programming Concepts. Classes. Objects. Chapter 8 User-Defined Classes and ADTs

OO Programming Concepts. Classes. Objects. Chapter 8 User-Defined Classes and ADTs Chapter 8 User-Defined Classes and ADTs Objectives To understand objects and classes and use classes to model objects To learn how to declare a class and how to create an object of a class To understand

More information

ECOM 2324 COMPUTER PROGRAMMING II

ECOM 2324 COMPUTER PROGRAMMING II ECOM 2324 COMPUTER PROGRAMMING II Object Oriented Programming with JAVA Instructor: Ruba A. Salamh Islamic University of Gaza 2 CHAPTER 9 OBJECTS AND CLASSES Motivations 3 After learning the preceding

More information

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017 Introduction to OOP with Java Instructor: AbuKhleif, Mohammad Noor Sep 2017 Lecture 07: OOP Part 1 Instructor: AbuKhleif, Mohammad Noor Sep 2017 Instructor AbuKhleif, Mohammad Noor Computer Engineer (JU

More information

Chapter 8 Objects and Classes

Chapter 8 Objects and Classes Chapter 8 Objects and Classes 1 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections, loops, methods, and arrays. However, these Java

More information

OOP Part 2. Introduction to OOP with Java. Lecture 08: Introduction to OOP with Java - AKF Sep AbuKhleiF -

OOP Part 2. Introduction to OOP with Java. Lecture 08: Introduction to OOP with Java - AKF Sep AbuKhleiF - Introduction to OOP with Java Instructor: AbuKhleif, Mohammad Noor Sep 2017 Lecture 08: OOP Part 2 Instructor: AbuKhleif, Mohammad Noor Sep 2017 AbuKhleiF - 1 Instructor AbuKhleif, Mohammad Noor Computer

More information

Chapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9

Chapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9 Chapter 6 Arrays Chapter 7 Objects and Classes Chapter 8 Strings and Text I/O Chapter 9 Inheritance and Polymorphism GUI can be covered after 10.2, Abstract Classes Chapter 12 GUI Basics 10.2, Abstract

More information

CS 170, Section /3/2009 CS170, Section 000, Fall

CS 170, Section /3/2009 CS170, Section 000, Fall Lecture 18: Objects CS 170, Section 000 3 November 2009 11/3/2009 CS170, Section 000, Fall 2009 1 Lecture Plan Homework 5 : questions, comments? Managing g g Data: objects to make your life easier ArrayList:

More information

Chapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9

Chapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9 Chapter 7 Objects and Classes Chapter 6 Arrays Chapter 7 Objects and Classes Chapter 8 Strings and Text I/O Chapter 9 Inheritance and Polymorphism GUI can be covered after 10.2, Abstract Classes Chapter

More information

CIS3023: Programming Fundamentals for CIS Majors II Summer 2010

CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Objects and Classes (contd.) Course Lecture Slides 19 May 2010 Ganesh Viswanathan Objects and Classes Credits: Adapted from CIS3023 lecture

More information

Object Oriented System Development Paradigm. Sunnie Chung CIS433 System Analysis Methods

Object Oriented System Development Paradigm. Sunnie Chung CIS433 System Analysis Methods Object Oriented System Development Paradigm Sunnie Chung CIS433 System Analysis Methods OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents

More information

Chapter 3 Objects and Classes

Chapter 3 Objects and Classes Chapter 3 Objects and Classes Topics OO Programming Concepts Creating Objects and Object Reference Variables Constructors Modifiers Instance and Class Variables and Methods Scope of Variables OO Programming

More information

We are on the GUI fast track path

We are on the GUI fast track path We are on the GUI fast track path Chapter 13: Exception Handling Skip for now Chapter 14: Abstract Classes and Interfaces Sections 1 9: ActionListener interface Chapter 15: Graphics Skip for now Chapter

More information

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn how to describe objects and classes and how to define classes and create objects

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn how to describe objects and classes and how to define classes and create objects Islamic University of Gaza Faculty of Engineering Computer Engineering Dept Computer Programming Lab (ECOM 2114) ABSTRACT In this Lab you will learn how to describe objects and classes and how to define

More information

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber Chapter 10 Inheritance and Polymorphism Dr. Hikmat Jaber 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the

More information

OBJECTS AND CLASSES Objectives To describe objects and classes, and use classes to model objects ( 7.2). To define classes with data fields and methods ( 7.2.1). To construct an object using a constructor

More information

Chapter 12 GUI Basics

Chapter 12 GUI Basics Chapter 12 GUI Basics 1 Creating GUI Objects // Create a button with text OK JButton jbtok = new JButton("OK"); // Create a label with text "Enter your name: " JLabel jlblname = new JLabel("Enter your

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Inheritance and Polymorphism Dr. M. G. Abbas Malik Assistant Professor Faculty of Computing and IT (North Jeddah Branch) King Abdulaziz University, Jeddah, KSA mgmalik@kau.edu.sa www.sanlp.org/malik/cpit305/ap.html

More information

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles, Chapter 11 Inheritance and Polymorphism 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the best way to design

More information

Programming in the Large II: Objects and Classes (Part 1)

Programming in the Large II: Objects and Classes (Part 1) Programming in the Large II: Objects and Classes (Part 1) 188230 Advanced Computer Programming Asst. Prof. Dr. Kanda Runapongsa Saikaew (krunapon@kku.ac.th) Department of Computer Engineering Khon Kaen

More information

2 What are the differences between constructors and methods?

2 What are the differences between constructors and methods? 1 Describe the relationship between an object and its defining class. How do you define a class? How do you declare an object reference variable? How do you create an object? How do you declare and create

More information

Abstract Class. Lecture 21. Based on Slides of Dr. Norazah Yusof

Abstract Class. Lecture 21. Based on Slides of Dr. Norazah Yusof Abstract Class Lecture 21 Based on Slides of Dr. Norazah Yusof 1 Abstract Class Abstract class is a class with one or more abstract methods. The abstract method Method signature without implementation

More information

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes Based on Introduction to Java Programming, Y. Daniel Liang, Brief Version, 10/E 1 Creating Classes and Objects Classes give us a way of defining custom data types and associating data with operations on

More information

Introduction to Programming Using Python Lecture 4. Dr. Zhang COSC 1437 Fall, 2018 October 11, 2018

Introduction to Programming Using Python Lecture 4. Dr. Zhang COSC 1437 Fall, 2018 October 11, 2018 Introduction to Programming Using Python Lecture 4 Dr. Zhang COSC 1437 Fall, 2018 October 11, 2018 Chapter 7 Object-Oriented Programming Object-oriented programming (OOP) involves programming using objects.

More information

Chapter 8 Objects and Classes Dr. Essam Halim Date: Page 1

Chapter 8 Objects and Classes Dr. Essam Halim Date: Page 1 Assignment (1) Chapter 8 Objects and Classes Dr. Essam Halim Date: 18-3-2014 Page 1 Section 8.2 Defining Classes for Objects 1 represents an entity in the real world that can be distinctly identified.

More information

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

1. Which of the following is the correct expression of character 4? a. 4 b. 4 c. '\0004' d. '4' Practice questions: 1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4' 2. Will System.out.println((char)4) display 4? a. Yes b. No 3. The expression "Java

More information

Inheritance and Polymorphism. CSE 114, Computer Science 1 Stony Brook University

Inheritance and Polymorphism. CSE 114, Computer Science 1 Stony Brook University Inheritance and Polymorphism CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation Model classes with similar properties and methods: Circles, rectangles

More information

Inf1-OOP. Data Types. Defining Data Types in Java. type value set operations. Overview. Circle Class. Creating Data Types 1.

Inf1-OOP. Data Types. Defining Data Types in Java. type value set operations. Overview. Circle Class. Creating Data Types 1. Overview Inf1-OOP Creating Data Types 1 Circle Class Object Default Perdita Stevens, adapting earlier version by Ewan Klein Format Strings School of Informatics January 11, 2015 HotelRoom Class More on

More information

Lecture 6 Introduction to Objects and Classes

Lecture 6 Introduction to Objects and Classes Lecture 6 Introduction to Objects and Classes Outline Basic concepts Recap Computer programs Programming languages Programming paradigms Object oriented paradigm-objects and classes in Java Constructors

More information

Constructor. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Constructor. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. Constructor Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the best way to design these classes so to avoid redundancy? The

More information

Chapter 9 Objects and Classes. Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.

Chapter 9 Objects and Classes. Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. Chapter 9 Objects and Classes 1 Objectives Classes & Objects ( 9.2). UML ( 9.2). Constructors ( 9.3). How to declare a class & create an object ( 9.4). Separate a class declaration from a class implementation

More information

Object-Oriented Programming Concepts

Object-Oriented Programming Concepts Object-Oriented Programming Concepts Real world objects include things like your car, TV etc. These objects share two characteristics: they all have state and they all have behavior. Software objects are

More information

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class CHAPTER GRAPHICAL USER INTERFACES 10 Slides by Donald W. Smith TechNeTrain.com Final Draft 10/30/11 10.1 Frame Windows Java provides classes to create graphical applications that can run on any major graphical

More information

Object Oriented Programming

Object Oriented Programming Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Lab 11 Object Oriented Programming Eng. Mohammed Alokshiya December 16, 2014 Object-oriented

More information

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;

More information

CS1150 Principles of Computer Science Objects and Classes

CS1150 Principles of Computer Science Objects and Classes CS1150 Principles of Computer Science Objects and Classes Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Object-Oriented Thinking Chapters 1-8

More information

Chapter 11 Inheritance and Polymorphism

Chapter 11 Inheritance and Polymorphism Chapter 11 Inheritance and Polymorphism 1 Motivations OOP is built on three principles: Encapsulation (classes/objects, discussed in chapters 9 and 10), Inheritance, and Polymorphism. Inheritance: Suppose

More information

Lab Exercise 1. Objectives: Part 1. Introduction

Lab Exercise 1. Objectives: Part 1. Introduction Objectives: king Saud University College of Computer &Information Science CSC111 Lab Object II All Sections - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

More information

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Covered in this chapter Classes Objects Methods Parameters double primitive type } Create a new class (GradeBook) } Use it to create an object.

More information

CS 112 Programming 2. Lecture 06. Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism

CS 112 Programming 2. Lecture 06. Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism CS 112 Programming 2 Lecture 06 Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism rights reserved. 2 Motivation Suppose you want to define classes to model circles, rectangles, and

More information

Chapter 11 Inheritance and Polymorphism

Chapter 11 Inheritance and Polymorphism Chapter 11 Inheritance and Polymorphism Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk 1 Motivations Suppose you will define classes

More information

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017 Introduction to OOP with Java Instructor: AbuKhleif, Mohammad Noor Sep 2017 Lecture 11: Inheritance and Polymorphism Part 1 Instructor: AbuKhleif, Mohammad Noor Sep 2017 Instructor AbuKhleif, Mohammad

More information

Chapter 1-9, 12-13, 18, 20, 23 Review Slides. What is a Computer?

Chapter 1-9, 12-13, 18, 20, 23 Review Slides. What is a Computer? Chapter 1-9, 12-13, 18, 20, 23 Review Slides CS1: Java Programming Colorado State University Original slides by Daniel Liang Modified slides by Chris Wilcox rights reserved. 1 What is a Computer? A computer

More information

Lecture Notes Chapter #9_b Inheritance & Polymorphism

Lecture Notes Chapter #9_b Inheritance & Polymorphism Lecture Notes Chapter #9_b Inheritance & Polymorphism Inheritance results from deriving new classes from existing classes Root Class all java classes are derived from the java.lang.object class GeometricObject1

More information

Computer Science II (20073) Week 1: Review and Inheritance

Computer Science II (20073) Week 1: Review and Inheritance Computer Science II 4003-232-01 (20073) Week 1: Review and Inheritance Richard Zanibbi Rochester Institute of Technology Review of CS-I Hardware and Software Hardware Physical devices in a computer system

More information

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written. HAND IN Answers Are Recorded on Question Paper QUEEN'S UNIVERSITY SCHOOL OF COMPUTING CISC212, FALL TERM, 2006 FINAL EXAMINATION 7pm to 10pm, 19 DECEMBER 2006, Jeffrey Hall 1 st Floor Instructor: Alan

More information

I pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class.

I pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class. Name: Covers Chapters 1-3 50 mins CSCI 1301 Introduction to Programming Armstrong Atlantic State University Instructor: Dr. Y. Daniel Liang I pledge by honor that I will not discuss this exam with anyone

More information

Final Examination Semester 2 / Year 2010

Final Examination Semester 2 / Year 2010 Southern College Kolej Selatan 南方学院 Final Examination Semester 2 / Year 2010 COURSE : JAVA PROGRAMMING COURSE CODE : PROG1114 TIME : 2 1/2 HOURS DEPARTMENT : COMPUTER SCIENCE LECTURER : LIM PEI GEOK Student

More information

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College CISC 3115 TY3 C09a: Inheritance Hui Chen Department of Computer & Information Science CUNY Brooklyn College 9/20/2018 CUNY Brooklyn College 1 Outline Inheritance Superclass/supertype, subclass/subtype

More information

Chapter 2. Elementary Programming

Chapter 2. Elementary Programming Chapter 2 Elementary Programming 1 Objectives To write Java programs to perform simple calculations To obtain input from the console using the Scanner class To use identifiers to name variables, constants,

More information

Give one example where you might wish to use a three dimensional array

Give one example where you might wish to use a three dimensional array CS 110: INTRODUCTION TO COMPUTER SCIENCE SAMPLE TEST 3 TIME ALLOWED: 60 MINUTES Student s Name: MAXIMUM MARK 100 NOTE: Unless otherwise stated, the questions are with reference to the Java Programming

More information

Chapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9

Chapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9 Chapter 6 Arrays Chapter 7 Objects and Classes Chapter 8 Strings Chapter 9 Inheritance and Polymorphism GUI can be covered after 10.2, Abstract Classes Chapter 12 GUI Basics 10.2, Abstract Classes Chapter

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba Laboratory Session: Exercises on classes Analogy to help you understand classes and their contents. Suppose you want to drive a car and make it go faster by pressing down

More information

COMP200 ABSTRACT CLASSES. OOP using Java, from slides by Shayan Javed

COMP200 ABSTRACT CLASSES. OOP using Java, from slides by Shayan Javed 1 1 COMP200 ABSTRACT CLASSES OOP using Java, from slides by Shayan Javed Abstract Classes 2 3 From the previous lecture: public class GeometricObject { protected String Color; protected String name; protected

More information

What is a Computer? Chapter 1-9, 12-13, 18, 20, 23 Review Slides

What is a Computer? Chapter 1-9, 12-13, 18, 20, 23 Review Slides Chapter 1-9, 12-13, 18, 20, 23 Review Slides What is a Computer? A computer consists of a CPU, memory, hard disk, floppy disk, monitor, printer, and communication devices. CS1: Java Programming Colorado

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

Programming with Java

Programming with Java Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

More information

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008 Overview Lecture 7: Inheritance and GUIs Written by: Daniel Dalevi Inheritance Subclasses and superclasses Java keywords Interfaces and inheritance The JComponent class Casting The cosmic superclass Object

More information

CH. 2 OBJECT-ORIENTED PROGRAMMING

CH. 2 OBJECT-ORIENTED PROGRAMMING CH. 2 OBJECT-ORIENTED PROGRAMMING ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016) OBJECT-ORIENTED

More information

Simple Java Reference

Simple Java Reference Simple Java Reference This document provides a reference to all the Java syntax used in the Computational Methods course. 1 Compiling and running... 2 2 The main() method... 3 3 Primitive variable types...

More information

Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay

Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay Classes - 2 Data Processing Course, I. Hrivnacova, IPN Orsay OOP, Classes Reminder Requirements for a Class Class Development Constructor Access Control Modifiers Getters, Setters Keyword this const Member

More information

CHAPTER 7 OBJECTS AND CLASSES

CHAPTER 7 OBJECTS AND CLASSES CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and

More information

Chapter 2 ELEMENTARY PROGRAMMING

Chapter 2 ELEMENTARY PROGRAMMING Chapter 2 ELEMENTARY PROGRAMMING Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk ١ Objectives To write Java programs to perform simple

More information

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

IST311. Advanced Issues in OOP: Inheritance and Polymorphism IST311 Advanced Issues in OOP: Inheritance and Polymorphism IST311/602 Cleveland State University Prof. Victor Matos Adapted from: Introduction to Java Programming: Comprehensive Version, Eighth Edition

More information

Lecture 7: Classes and Objects CS2301

Lecture 7: Classes and Objects CS2301 Lecture 7: Classes and Objects NADA ALZAHRANI CS2301 1 What is OOP? Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that can be distinctly

More information

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018 Birkbeck (University of London) Software and Programming 1 In-class Test 2.1 22 Mar 2018 Student Name Student Number Answer ALL Questions 1. What output is produced when the following Java program fragment

More information

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette COMP 250: Java Programming I Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette Variables and types [Downey Ch 2] Variable: temporary storage location in memory.

More information

An Introduction To Writing Your Own Classes CSC 123 Fall 2018 Howard Rosenthal

An Introduction To Writing Your Own Classes CSC 123 Fall 2018 Howard Rosenthal An Introduction To Writing Your Own Classes CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Understand Object Oriented Programming The Syntax of Class Definitions Constructors this Object Oriented "Hello

More information

Inf1-OP. Creating Classes. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. February 26, School of Informatics

Inf1-OP. Creating Classes. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. February 26, School of Informatics Inf1-OP Creating Classes Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein School of Informatics February 26, 2018 Creating classes Last time we saw how to use a class: create a

More information

Questions Answer Key Questions Answer Key Questions Answer Key

Questions Answer Key Questions Answer Key Questions Answer Key Benha University Term: 2 nd (2013/2014) Class: 2 nd Year Students Subject: Object Oriented Programming Faculty of Computers & Informatics Date: 26/4/2014 Time: 1 hours Exam: Mid-Term (A) Name:. Status:

More information

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written. SOLUTION HAND IN Answers Are Recorded on Question Paper QUEEN'S UNIVERSITY SCHOOL OF COMPUTING CISC212, FALL TERM, 2006 FINAL EXAMINATION 7pm to 10pm, 19 DECEMBER 2006, Jeffrey Hall 1 st Floor Instructor:

More information

Graphical User Interfaces. Comp 152

Graphical User Interfaces. Comp 152 Graphical User Interfaces Comp 152 Procedural programming Execute line of code at a time Allowing for selection and repetition Call one function and then another. Can trace program execution on paper from

More information

Graphical User Interface (GUI) and Object- Oriented Design (OOD)

Graphical User Interface (GUI) and Object- Oriented Design (OOD) Chapter 6,13 Graphical User Interface (GUI) and Object- Oriented Design (OOD) Objectives To distinguish simple GUI components. To describe the Java GUI API hierarchy. To create user interfaces using frames,

More information

Full download all chapters instantly please go to Solutions Manual, Test Bank site: testbanklive.com

Full download all chapters instantly please go to Solutions Manual, Test Bank site: testbanklive.com Introduction to Java Programming Comprehensive Version 10th Edition Liang Test Bank Full Download: http://testbanklive.com/download/introduction-to-java-programming-comprehensive-version-10th-edition-liang-tes

More information

Class Foo. instance variables. instance methods. Class FooTester. main {

Class Foo. instance variables. instance methods. Class FooTester. main { Creating classes Inf1-OP Creating Classes Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein School of Informatics February 26, 2018 Last time we saw how to use a class: create a

More information

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word Chapter 1 Introduction to Computers, Programs, and Java Chapter 2 Primitive Data Types and Operations Chapter 3 Selection

More information

Object-Oriented Programming Concepts

Object-Oriented Programming Concepts Object-Oriented Programming Concepts Object-oriented programming מונחה עצמים) (תכנות involves programming using objects An object ) represents (עצם an entity in the real world that can be distinctly identified

More information

Chapter 2 Elementary Programming

Chapter 2 Elementary Programming Chapter 2 Elementary Programming Part I 1 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from this chapter, you will learn how to solve practical

More information

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended JAVA Classes Class definition complete definition [public] [abstract] [final] class Name [extends Parent] [impelements ListOfInterfaces] {... // class body public public class abstract no instance can

More information

Ryerson University Vers HAL6891A-05 School of Computer Science CPS109 Midterm Test Fall 05 page 1 of 6

Ryerson University Vers HAL6891A-05 School of Computer Science CPS109 Midterm Test Fall 05 page 1 of 6 CPS109 Midterm Test Fall 05 page 1 of 6 Last Name First Name Student Number Circle Your Instructor Your last name here Your first name here Your student number here Ferworn Harley Instructions: (a) There

More information

CHAPTER 7 OBJECTS AND CLASSES

CHAPTER 7 OBJECTS AND CLASSES CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and

More information

COE318 Lecture Notes Week 4 (Sept 26, 2011)

COE318 Lecture Notes Week 4 (Sept 26, 2011) COE318 Software Systems Lecture Notes: Week 4 1 of 11 COE318 Lecture Notes Week 4 (Sept 26, 2011) Topics Announcements Data types (cont.) Pass by value Arrays The + operator Strings Stack and Heap details

More information

Unit 6: Graphical User Interface

Unit 6: Graphical User Interface Faculty of Computer Science Programming Language 2 Object oriented design using JAVA Dr. Ayman Ezzat Email: ayman@fcih.net Web: www.fcih.net/ayman Unit 6: Graphical User Interface 1 1. Overview of the

More information

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string COMP 202 Built in Libraries and objects CONTENTS: Introduction to objects Introduction to some basic Java libraries string COMP 202 Objects and Built in Libraries 1 Classes and Objects An object is an

More information

Computer Science II (20082) Week 1: Review and Inheritance

Computer Science II (20082) Week 1: Review and Inheritance Computer Science II 4003-232-08 (20082) Week 1: Review and Inheritance Richard Zanibbi Rochester Institute of Technology Review of CS-I Syntax and Semantics of Formal (e.g. Programming) Languages Syntax

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes 1 CS257 Computer Science II Kevin Sahr, PhD Lecture 5: Writing Object Classes Object Class 2 objects are the basic building blocks of programs in Object Oriented Programming (OOP) languages objects consist

More information

Making New instances of Classes

Making New instances of Classes Making New instances of Classes NOTE: revised from previous version of Lecture04 New Operator Classes are user defined datatypes in OOP languages How do we make instances of these new datatypes? Using

More information

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade; Control Statements Control Statements All programs could be written in terms of only one of three control structures: Sequence Structure Selection Structure Repetition Structure Sequence structure The

More information

COMP 250. inheritance (cont.) interfaces abstract classes

COMP 250. inheritance (cont.) interfaces abstract classes COMP 250 Lecture 31 inheritance (cont.) interfaces abstract classes Nov. 20, 2017 1 https//goo.gl/forms/ymqdaeilt7vxpnzs2 2 class Object boolean equals( Object ) int hashcode( ) String tostring( ) Object

More information

Selected Questions from by Nageshwara Rao

Selected Questions from  by Nageshwara Rao Selected Questions from http://way2java.com by Nageshwara Rao Swaminathan J Amrita University swaminathanj@am.amrita.edu November 24, 2016 Swaminathan J (Amrita University) way2java.com (Nageshwara Rao)

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 02: Using Objects MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Using Objects 2 Introduction to Object Oriented Programming Paradigm Objects and References Memory Management

More information