Chapter 8 Objects and Classes

Size: px
Start display at page:

Download "Chapter 8 Objects and Classes"

Transcription

1 Chapter 8 Objects and Classes 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 notations to describe classes and objects ( 8.2). To demonstrate defining classes and creating objects ( 8.3). To create objects using constructors ( 8.4). To access objects via object reference variables ( 8.5). To define a reference variable using a reference type ( 8.5.1). To access an object s data and methods using the object member access operator (.) ( 8.5.2). To define data fields of reference types and assign default values for an object s data fields ( 8.5.3). To distinguish between object reference variables and primitive data type variables ( 8.5.4). To use classes Date, Random, and JFrame in the Java library ( 8.6). To distinguish between instance and static variables and methods ( 8.7). To define private data fields with appropriate get and set methods ( 8.8). To encapsulate data fields to make classes easy to maintain ( 8.9). To develop methods with object arguments and differentiate between primitive-type arguments and object-type arguments ( 8.10). To store and process objects in arrays ( 8.11). 3

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

5 Once a class of items is defined, a specific instance of the class can be defined. An instance is also called object. An object has a unique identity, state, and behaviors. The state of an object consists of a set of data fields (also known as properties) with their current values. The behavior of an object is defined by a set of methods, in other words what the object does. In other words an object is a software bundle of variables and related methods. 5

6 Class and Object Example The table gives some examples of classes and objects Type Example of class Example of object Occurrence Alarm Fire alarm Things Car Ferrari 360 External entities Door Fire door Roles Teacher Mohammad, Hassan Organizational Department CS, IT, IS units Real World Objects 6

7 UML Class and Object Diagrams: A class diagram is simply a rectangle divided into three compartments. The topmost compartment contains the name of the class. The middle compartment contains a list of attributes (member variables), and the bottom compartment contains a list of operations (member functions). The purpose of a class diagram is to show the classes within a model. UML Class Diagram Student Class name Name: String Data fields getname(): String methods setname() S1: Student Name = Ahmed S2: Student Name= Ali S3: Student Name= Suhel UML notation for objects 3 Objects of Student class 7

8 Kinds of classes: Standard Class: Don t reinvent the wheel. When there are existing objects that satisfy our needs, use them. Learning how to use standard Java classes is the first step toward mastering OOP. Some of the standard classes are JOptionPane, String, Scanner etc Programmer defined Class: Using just the String, JOptionPane, Scanner, JFrame and other standard classes will not meet all of our needs. We need to be able to define our own classes customized for our applications. Classes we define ourselves are called programmerdefined classes 8

9 Template for Class Definition Import Statements Class Comment class { Class Name Data Members Methods (incl. Constructor) 9

10 Example of a Class import java.util.*; //student class definition class Student { /** The name of a student */ String name ; Data field /** Methods of Student class */ public void setname(string n) { name=n; Methods public String getname() { return name; 10

11 Object Declaration Class Name This class must be defined before this declaration can be stated. Object Name One object is declared here. Student jan; More Examples Account Student Vehicle customer; jan, jim, jon; car1, car2; 11

12 Object Creation Object Name Name of the object we are creating here. Class Name An instance of this class is created. Argument No arguments are used here. jan = new Student ( ) ; More Examples customer = new Account(); jon = new Student( John Java ); car1 = new Vehicle( ); 12

13 Declaration vs. Creation 1 2 Student hussain; hussain = new Student( ); 1 hussain 1. The identifier hussain is declared and space is allocated in memory. 2 : Student 2. A Student object is created and the identifier hussain is set to refer to it. Declaration and Creation in one step Assign object reference Create an object Student hussain= new Student(); 13

14 Accessing members of a class. (dot) operator is used to access public members of a class A general syntax to access public members of a class is as follows // s is object of Student class Student s= new Student(); Referencing the object s data: objectrefvar.data e.g., s.name= Ali ; // accessing public data member Invoking the object s method: objectrefvar.methodname(arguments) e.g., s.setname( Ahmad ); // accessing method s.getname(); // accessing method 14

15 Example 1: Defining Classes and Creating Objects Objective: Demonstrate creating objects, accessing data, and using methods. //student class definition class Student { /** name is a data member to store name of a student */ String name ; /** Methods of Student class */ public void setname(string n) { name=n; public String getname() { return name; //Test class Teststudent definition class TestStudent { public static void main (String [] args) { // Creating object Student s = new Student (); s.name= Ali ; System.out.println( Name: + s.name); s.setname( Ahmad ); System.out.println( Name: + s.getname()); 15

16 Second Example: Using the Bicycle Class Bicycle CLASS ownername getownername( ) setownername(string) Data member Methods bike1 bike2 OBJECTS ownername= Adam Smith ownername = Ben Jones 16

17 Example 2: Defining Classes and Creating Objects Objective: Demonstrate creating objects, accessing data, and using methods. class Bicycle { // Data Member private String ownername; //Returns name of this bicycle's owner public String getownername( ) { return ownername; //Assigns name of this bicycle's owner public void setownername(string name) { ownername = name; class BicycleRegistration { public static void main(string[] args) { Bicycle bike1, bike2; String owner1, owner2; bike1 = new Bicycle( ); //Create and assign values to bike1 bike1.setownername("adam Smith"); bike2 = new Bicycle( ); //Create and assign values to bike2 bike2.setownername("ben Jones"); owner1 = bike1.getownername( ); //Output the information owner2 = bike2.getownername( ); System.out.println(owner1 + " owns a bicycle."); System.out.println(owner2 + " also owns a bicycle."); 17

18 Constructors The constructor method is like a normal public method except that it shares the same name as the class and it has no return value not even void since constructors never return a value. It can have none, one or many parameters. Constructors are a special kind of methods that are invoked to construct objects. Normally for a constructor method to be useful we would design it so that it expects parameters. The values passed through these parameters can be used to set the values of the private fields. 18

19 Constructors, cont. A constructor with no parameters is referred to as a no-arg constructor. Point to be noted about constructor. 1. Constructors must have the same name as the class itself. 2. Constructors do not have a return type not even void. 3. Constructors are invoked (called) using the new operator when an object is created. 4. Constructors play the role of initializing objects. 19

20 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

21 Example 3: Defining Classes with constructors and Creating Objects. class Account { private String ownername; private double balance; public Account( ) { ownername = "Unassigned"; balance = 0.0; public void add(double amt) { balance = balance + amt; class TestAccount{ /* This sample program uses both the Bicycle and Account classes */ public static void main(string[] args) { Account acct; String myname = "Jon Java"; public void deduct(double amt) { balance = balance - amt; public void setbalance (double bal) { balance = bal; public void setownername (String name) { ownername = name; public double getbalance( ) { return balance; public String getownername( ) { return ownername; acct = new Account( ); acct.setownername(myname); acct.setbalance(250.00); acct.add(25.00); acct.deduct(50); //Output some information System.out.println("has $ " + acct.getbalance() + " left in the bank"); 21

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

23 animation Trace Code Another Example Declare mycircle Circle mycircle = new Circle(5.0); Circle yourcircle = new Circle(); yourcircle.radius = 100; mycircle no value 23

24 animation Trace Code, cont. Circle mycircle = new Circle(5.0); Circle yourcircle = new Circle(); mycircle no value yourcircle.radius = 100; : Circle radius: 5.0 Create a circle 24

25 animation Trace Code, cont. Circle mycircle = new Circle(5.0); Circle yourcircle = new Circle(); mycircle reference value yourcircle.radius = 100; Assign object reference to mycircle radius: 5.0 : Circle 25

26 animation Trace Code, cont. Circle mycircle = new Circle(5.0); Circle yourcircle = new Circle(); mycircle reference value yourcircle.radius = 100; : Circle radius: 5.0 yourcircle no value Declare yourcircle 26

27 animation Trace Code, cont. Circle mycircle = new Circle(5.0); Circle yourcircle = new Circle(); mycircle reference value yourcircle.radius = 100; : Circle radius: 5.0 yourcircle no value : Circle Create a new Circle object radius:

28 animation Trace Code, cont. Circle mycircle = new Circle(5.0); Circle yourcircle = new Circle(); mycircle reference value yourcircle.radius = 100; : Circle radius: 5.0 yourcircle reference value Assign object reference to yourcircle : Circle radius:

29 animation Trace Code, cont. Circle mycircle = new Circle(5.0); Circle yourcircle = new Circle(); mycircle reference value yourcircle.radius = 100; : Circle radius: 5.0 yourcircle reference value Change radius in yourcircle : Circle radius:

30 Caution Recall that you use Math.methodName(arguments) (e.g., Math.pow(3, 2.5)) to invoke a method in the Math class. Can you invoke getarea() using Circle1.getArea()? The answer is no. All the methods used before this chapter are static methods, which are defined using the static keyword. However, getarea() is non-static. It must be invoked from an object using objectrefvar.methodname(arguments) (e.g., mycircle.getarea()). More explanations will be given in the section on Static Variables, Constants, and Methods. 30

31 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' 31

32 The null Value If a data field of a reference type does not reference any object, the data field holds a special literal value, null. 32

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

34 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 34

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

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

37 Garbage Collection As shown in the previous figure, after the assignment statement c1 = c2, c1 points to the same object referenced by c2. The object previously referenced by c1 is no longer referenced. This object is known as garbage. Garbage is automatically collected by JVM. 37

38 Garbage Collection, cont TIP: If you know that an object is no longer needed, you can explicitly assign null to a reference variable for the object. The JVM will automatically collect the space if the object is not referenced by any variable. 38

39 The Date Class Java provides a system-independent encapsulation of date and time in the java.util.date class. You can use the Date class to create an instance for the current date and time and use its tostring method to return the date and time as a string. 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. 39

40 The Date Class Example For example, the following code java.util.date date = new java.util.date(); System.out.println(date.toString()); displays a string like Sun Mar 09 13:50:19 EST

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

42 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: From random2:

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

44 // Generate frame using standard class JFrame import javax.swing.jframe; public class TestFrame { public static void main(string[] args) { JFrame frame1 = new JFrame(); frame1.settitle("window 1"); frame1.setsize(200, 150); frame1.setlocation(200, 100); frame1.setdefaultcloseoperation(jframe.exit_on_close); frame1.setvisible(true); JFrame frame2 = new JFrame(); frame2.settitle("window 2"); frame2.setsize(200, 150); frame2.setlocation(410, 100); frame2.setdefaultcloseoperation(jframe.exit_on_close); frame2.setvisible(true); 44

45 animation 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); frame1 reference : JFrame title: width: height: visible: Declare, create, and assign in one statement 45

46 animation 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); frame1 reference : JFrame title: "Window 1" width: height: visible: Set title property 46

47 animation 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); frame1 reference : JFrame title: "Window 1" width: 200 height: 150 visible: Set size property 47

48 animation 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); frame1 reference : JFrame title: "Window 1" width: 200 height: 150 visible: true Set visible property 48

49 animation 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); frame1 frame2 reference : JFrame title: "Window 1" width: 200 height: 150 visible: true reference : JFrame title: width: height: visible: Declare, create, and assign in one statement 49

50 animation 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); frame1 frame2 reference : JFrame title: "Window 1" width: 200 height: 150 visible: true reference : JFrame title: "Window 2" width: height: visible: Set title property 50

51 animation 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); frame1 frame2 reference : JFrame title: "Window 1" width: 200 height: 150 visible: true reference : JFrame title: "Window 2" width: 200 height: 150 visible: Set size property 51

52 animation 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); frame1 frame2 reference : JFrame title: "Window 1" width: 200 height: 150 visible: true reference : JFrame title: "Window 2" width: 200 height: 150 visible: true Set visible property 52

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

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

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

56 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 56

57 Objective: Demonstrate the roles of instance and class variables and their uses. This example adds a class variable numberofobjects to track the number of Circle objects created. public class Circle2 { double radius; /** The radius of the circle */ static int numberofobjects = 0; /** No of objects created */ /** Construct a circle with radius 1 */ Circle2() { radius = 1.0; numberofobjects++; /** Construct a circle with a specified radius */ Circle2(double newradius) { radius = newradius; numberofobjects++; /** Return numberofobjects */ static int getnumberofobjects() { return numberofobjects; /** Return the area of this circle */ double getarea() { return radius * radius * Math.PI; 57

58 public class TestCircle2 { /** Main method */ public static void main(string[] args) { System.out.println("Before creating objects"); System.out.println("The number of Circle objects is " + Circle2.numberOfObjects); // Create c1 Circle2 c1 = new Circle2(); // Display c1 BEFORE c2 is created System.out.println("\nAfter creating c1"); System.out.println("c1: radius (" + c1.radius + ") and number of Circle objects (" + c1.numberofobjects + ")"); // Create c2 Circle2 c2 = new Circle2(5); // Modify c1 c1.radius = 9; // Display c1 and c2 AFTER c2 was created System.out.println("\nAfter creating c2 and modifying c1"); System.out.println("c1: radius (" + c1.radius + ") and number of Circle objects (" + c1.numberofobjects + ")"); System.out.println("c2: radius (" + c2.radius + ") and number of Circle objects (" + c2.numberofobjects + ")"); 58

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

60 Accessibility Example Service obj = new Service(); obj.memberone = 10; obj.membertwo = 20; obj.doone(); obj.dotwo(); Client class Service { public int memberone; private int membertwo; public void doone() { private void dotwo() { Service 60

61 Why Data Fields Should Be private? To protect data. To make class easy to maintain. Internal details of a class are declared private and hidden from the clients. This is information hiding. 61

62 Example of Data Field Encapsulation The - sign indicates private modifier Circle -radius: double -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. 62

63 Passing Objects to Methods As we can pass int and double values, we can also pass an object to a method. When we pass an object, we are actually passing the reference (name) of an object it means a duplicate of an object is NOT created in the called method. 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) 63

64 Passing Objects to a Method Student LibraryCard name Student( ) get ( ) getname( ) set (string) setname(string) owner borrowcnt LibraryCard( ) chcekout( int ) getnumberofbooks( ) getownername( ) setowner( Student ) tostring() 64

65 Passing a Student Object student Passing side 1 student Receiving side 2 Memory Allocation card2 :Student name Joan Java jj@javauniv.edu :LibraryCard owner borrowcnt 0

66 Passing a Student Object

67 Passing a Student Object LibraryCard card2; card2 = new LibraryCard(); student 1 st card2.setowner(student); Passing Side 1 card2 class LibraryCard { private Student owner; public void setowner(student st) { 2 owner = st; Receiving Side 2 : LibraryCard owner : Student name Jon Java 1 Argument is passed borrowcnt 0 jj@javauniv.edu 2 Value is assigned to the data member State of Memory

68 class Student { private String name; private String ; public Student() { name = "Unassigned"; = "Unassigned"; public String get ( ) { return ; public String getname( ) { class LibraryCard { //student owner of this card private Student owner; //number of books borrowed private int borrowcnt; //numofbooks are checked out public void checkout(int numofbooks) { borrowcnt = borrowcnt + numofbooks; //Returns the name of the owner of this card public String getownername( ) { return owner.getname( ); return name; //Assigns the name of this student public void setname(string studentname) { name = studentname; //Assigns the of this student public void set (string address) { = address; //Returns the number of books borrowed public int getnumberofbooks( ) { return borrowcnt; //Sets the owner of this card to student public void setowner(student stud) { owner = stud; //Returns the string representation of this card public String tostring( ) { return "Owner Name: " +owner.getname( )+"\n"+ " + owner.get ( ) + "\n" + "Books Borrowed: " + borrowcnt; 68

69 class Librarian { public static void main( String[] args ) { Student stud; stud = new Student( ); stud.setname("jon Java"); stud.set ("jj@javauniv.edu"); LibraryCard card1, card2; card1 = new LibraryCard( ); card1.setowner(stud); card1.checkout(3); card2 = new LibraryCard( ); card2.setowner(stud); //the same student is the owner of the second card, too System.out.println("Card1 Info:"); System.out.println(card1.toString() + "\n"); System.out.println("Card2 Info:"); System.out.println(card2.toString() + "\n"); 69

70 Sharing an Object We pass the same Student object to card1 and card2 Since we are actually passing a reference to the same object, it results in owner of two LibraryCard objects pointing to the same Student object 70

71 Array of Objects In Java, in addition to arrays of primitive data types, we can declare arrays of objects An array of primitive data is a powerful tool, but an array of objects is even more powerful. The use of an array of objects allows us to model the application more cleanly and logically. 71

72 class Person { private String name; private int age; private char gender; The Person class supports the set methods and get methods. public Person() { name = "Unassigned"; age = -1; gender= u ; // Return Person Age public int getage( ) { return age; // Return Person Gender public char getgender( ) { return gender; //Return Person Name public String getname( ) { return name; //Assigns the name of Person public void setname(string personname) { name = personname; //Assigns the age of Person public void setage(int personage) { age = personage; //Assigns the Gender of Person (M/F) public void setgender(char persongender) { gender = persongender; public class Test { public static void main (String[] args) { Person latte; latte = new Person( ); latte.setname("ms. Latte"); latte.setage(20); latte.setgender('f'); System.out.println("Name: "+ latte.getname()); System.out.println("Age : "+ latte.getage()); System.out.println("Sex : "+ latte.getgender()); 72

73 The Person Class We will use Person objects to illustrate the use of an array of objects. Person latte; latte = new Person( ); latte.setname("ms. Latte"); latte.setage(20); latte.setgender('f'); System.out.println( "Name: " + latte.getname() ); System.out.println( "Age : " + latte.getage() ); System.out.println( "Sex : " + latte.getgender() );

74 Creating an Object Array - 1 Code A Person[ ] person; person = new Person[20]; person[0] = new Person( ); Only the name person is declared, no array is allocated yet. person State of Memory After A is executed

75 Creating an Object Array - 2 Code B Person[ ] person; person = new Person[20]; person[0] = new Person( ); Now the array for storing 20 Person objects is created, but the Person objects themselves are not yet created. person State of Memory After B is executed

76 Creating an Object Array - 3 Code C Person[ ] person; person = new Person[20]; person[0] = new Person( ); One Person object is created and the reference to this object is placed in position 0. person State of Memory Person : Person Not Given o U After C is executed

77 The Person Class public class Test { public static void main (String[] args) { Person [ ]prsn=new Person [20]; Prsn[0] = new Person( ); Prsn[0].setName("Ms. Latte"); Prsn[0].setAge(20); Prsn[0].setGender('F'); Prsn[1] = new Person( ); Prsn[1].setName("Mr. Khalid"); Prsn[1].setAge(30); Prsn[1].setGender( M');....

78 Person Array Processing Sample 1 Create Person objects and set up the person array. class Test { public static void main (String[] args) { String name, inpstr; int age; char gender; Person [ ]prsn=new Person [20]; for (int i = 0; i < prsn.length; i++) { name = JOptionPane.showInputDialog(null,"Enter name:"); age = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter age:")); inpstr = JOptionPane.showInputDialog(null,"Enter gender:"); gender = inpstr.charat(0); prsn[i] = new Person( ); prsn[i].setname ( name ); prsn[i].setage ( age ); prsn[i].setgender( gender ); The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 10-78

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 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, 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 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 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

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

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

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

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

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. Chapter 8 Objects and Classes Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk 1 Motivations After learning the preceding chapters,

More information

Chapter 4. Defining Your Own Classes Part 1

Chapter 4. Defining Your Own Classes Part 1 Chapter 4 Defining Your Own Classes Part 1 Animated Version required for reproduction or display. Chapter 4-1 Objectives After you have read and studied this chapter, you should be able to Define a class

More information

Chapter 4. Defining Your Own Classes Part 1. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Chapter 4. Defining Your Own Classes Part 1. CS 180 Sunil Prabhakar Department of Computer Science Purdue University Chapter 4 Defining Your Own Classes Part 1 CS 180 Sunil Prabhakar Department of Computer Science Purdue University Objectives This week we will study how to create your own classes including: Local and

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

Object Oriented Relationships

Object Oriented Relationships Lecture 3 Object Oriented Relationships Group home page: http://groups.yahoo.com/group/java CS244/ 2 Object Oriented Relationships Object oriented programs usually consisted of a number of classes Only

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

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

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

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

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

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

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

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

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

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

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

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

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

Chapter 5: Classes and Objects in Depth. Information Hiding

Chapter 5: Classes and Objects in Depth. Information Hiding Chapter 5: Classes and Objects in Depth Information Hiding Objectives Information hiding principle Modifiers and the visibility UML representation of a class Methods Message passing principle Passing parameters

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

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

Chapter 5: Classes and Objects in Depth. Introduction to methods

Chapter 5: Classes and Objects in Depth. Introduction to methods Chapter 5: Classes and Objects in Depth Introduction to methods What are Methods Objects are entities of the real-world that interact with their environments by performing services on demand. Objects of

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

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

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

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

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

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes CS111: PROGRAMMING LANGUAGE II Lecture 1: Introduction to classes Lecture Contents 2 What is a class? Encapsulation Class basics: Data Methods Objects Defining and using a class In Java 3 Java is an object-oriented

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

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

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

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

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

CS Week 13. Jim Williams, PhD

CS Week 13. Jim Williams, PhD CS 200 - Week 13 Jim Williams, PhD This Week 1. Team Lab: Instantiable Class 2. BP2 Strategy 3. Lecture: Classes as templates BP2 Strategy 1. M1: 2 of 3 milestone tests didn't require reading a file. 2.

More information

Object Oriented Programming in C#

Object Oriented Programming in C# Introduction to Object Oriented Programming in C# Class and Object 1 You will be able to: Objectives 1. Write a simple class definition in C#. 2. Control access to the methods and data in a class. 3. 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

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

OBJECT ORİENTATİON ENCAPSULATİON

OBJECT ORİENTATİON ENCAPSULATİON OBJECT ORİENTATİON Software development can be seen as a modeling activity. The first step in the software development is the modeling of the problem we are trying to solve and building the conceptual

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

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and Classes CS 251 Intermediate Programming Methods and Classes Brooke Chenoweth University of New Mexico Fall 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

CS 251 Intermediate Programming Methods and More

CS 251 Intermediate Programming Methods and More CS 251 Intermediate Programming Methods and More Brooke Chenoweth University of New Mexico Spring 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

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

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide AP Computer Science Chapter 10 Implementing and Using Classes Study Guide 1. A class that uses a given class X is called a client of X. 2. Private features of a class can be directly accessed only within

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

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

Object Oriented Modeling

Object Oriented Modeling Object Oriented Modeling Object oriented modeling is a method that models the characteristics of real or abstract objects from application domain using classes and objects. Objects Software objects are

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

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

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

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

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

Inheritance and Polymorphism

Inheritance and Polymorphism Object Oriented Programming Designed and Presented by Dr. Ayman Elshenawy Elsefy Dept. of Systems & Computer Eng.. Al-Azhar University Website: eaymanelshenawy.wordpress.com Email : eaymanelshenawy@azhar.edu.eg

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

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved. 1 3 Introduction to Classes and Objects 2 You will see something new. Two things. And I call them Thing One and Thing Two. Dr. Theodor Seuss Geisel Nothing can have value without being an object of utility.

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

Tutorial 6 CSC 201. Java Programming Concepts مبادئ الربجمة باستخدام اجلافا

Tutorial 6 CSC 201. Java Programming Concepts مبادئ الربجمة باستخدام اجلافا Tutorial 6 CSC 201 Java Programming Concepts مبادئ الربجمة باستخدام اجلافا Chapter 6: Classes and Objects 1. Classes & Objects What is an object? Real Objects Java Objects Classes Defining a class and

More information

JAVA: A Primer. By: Amrita Rajagopal

JAVA: A Primer. By: Amrita Rajagopal JAVA: A Primer By: Amrita Rajagopal 1 Some facts about JAVA JAVA is an Object Oriented Programming language (OOP) Everything in Java is an object application-- a Java program that executes independently

More information

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved. 1 3 Introduction to Classes and Objects 2 You will see something new. Two things. And I call them Thing One and Thing Two. Dr. Theodor Seuss Geisel Nothing can have value without being an object of utility.

More information

9 Working with the Java Class Library

9 Working with the Java Class Library 9 Working with the Java Class Library 1 Objectives At the end of the lesson, the student should be able to: Explain object-oriented programming and some of its concepts Differentiate between classes and

More information

CSEN401 Computer Programming Lab. Topics: Introduction and Motivation Recap: Objects and Classes

CSEN401 Computer Programming Lab. Topics: Introduction and Motivation Recap: Objects and Classes CSEN401 Computer Programming Lab Topics: Introduction and Motivation Recap: Objects and Classes Prof. Dr. Slim Abdennadher 16.2.2014 c S. Abdennadher 1 Course Structure Lectures Presentation of topics

More information

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

CLASSES AND OBJECTS. Fundamentals of Computer Science I

CLASSES AND OBJECTS. Fundamentals of Computer Science I CLASSES AND OBJECTS Fundamentals of Computer Science I Outline Primitive types Creating your own data types Classes Objects Instance variables Instance methods Constructors Arrays of objects A Foundation

More information

MIDTERM REVIEW. midterminformation.htm

MIDTERM REVIEW.   midterminformation.htm MIDTERM REVIEW http://pages.cpsc.ucalgary.ca/~tamj/233/exams/ midterminformation.htm 1 REMINDER Midterm Time: 7:00pm - 8:15pm on Friday, Mar 1, 2013 Location: ST 148 Cover everything up to the last lecture

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

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors Agenda

More information

Introduction to Classes and Objects

Introduction to Classes and Objects 1 2 Introduction to Classes and Objects You will see something new. Two things. And I call them Thing One and Thing Two. Dr. Theodor Seuss Geisel Nothing can have value without being an object of utility.

More information

3.1 Class Declaration

3.1 Class Declaration Chapter 3 Classes and Objects OBJECTIVES To be able to declare classes To understand object references To understand the mechanism of parameter passing To be able to use static member and instance member

More information

CS 1302 Chapter 9 (Review) Object & Classes

CS 1302 Chapter 9 (Review) Object & Classes CS 1302 Chapter 9 (Review) Object & Classes Reference Sections 9.2-9.5, 9.7-9.14 9.2 Defining Classes for Objects 1. A class is a blueprint (or template) for creating objects. A class defines the state

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

Computer Science II. OO Programming Classes Scott C Johnson Rochester Institute of Technology

Computer Science II. OO Programming Classes Scott C Johnson Rochester Institute of Technology Computer Science II OO Programming Classes Scott C Johnson Rochester Institute of Technology Outline Object-Oriented (OO) Programming Review Initial Implementation Constructors Other Standard Behaviors

More information

What is Inheritance?

What is Inheritance? Inheritance 1 Agenda What is and Why Inheritance? How to derive a sub-class? Object class Constructor calling chain super keyword Overriding methods (most important) Hiding methods Hiding fields Type casting

More information

Chapter 10. Arrays and Collections. Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Chapter 10. Arrays and Collections. Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 10 Arrays and Collections Animated Version required for reproduction or display. Chapter 10-1 Objectives After you have read and studied this chapter, you should be able to Manipulate a collection

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

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

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

CS121/IS223. Object Reference Variables. Dr Olly Gotel

CS121/IS223. Object Reference Variables. Dr Olly Gotel CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors CS121/IS223

More information

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

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

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

Lecture Set 2: Starting Java

Lecture Set 2: Starting Java Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural

More information

CONSTRUCTOR & Description. String() This initializes a newly created String object so that it represents an empty character sequence.

CONSTRUCTOR & Description. String() This initializes a newly created String object so that it represents an empty character sequence. Constructor in Java 1. What are CONSTRUCTORs? Constructor in java is a special type of method that is used to initialize the object. Java constructor is invoked at the time of object creation. It constructs

More information

Chapter 3 Classes & Objects

Chapter 3 Classes & Objects 1 Chapter 3 Classes & Objects Question 1: Given the code below, 1. public class Try 3. private static int sum = 20; 4. public static void main(string args[]) 5. { 6. Try t1 = new Try(); 7. Try.sum++; 8.

More information

User Defined Classes. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

User Defined Classes. CS 180 Sunil Prabhakar Department of Computer Science Purdue University User Defined Classes CS 180 Sunil Prabhakar Department of Computer Science Purdue University Announcements Register for Piazza. Deleted post accidentally -- sorry. Direct Project questions to responsible

More information

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2018 Instructors: Bill & Bill

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2018 Instructors: Bill & Bill CSCI 136 Data Structures & Advanced Programming Lecture 3 Fall 2018 Instructors: Bill & Bill Administrative Details Lab today in TCL 217a (and 216) Lab is due by 11pm Sunday Lab 1 design doc is due at

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

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation COMP-202 Unit 8: Defining Your Own Classes CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation Defining Our Own Classes (1) So far, we have been creating

More information