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 identified. For example, a student, a desk, a circle, chair, board. What is the properties and behavior of each of them? 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. 2
Different Programming Paradigms Functional/procedural programming: program is a list of instructions to the computer Object-oriented programming: program is composed of a collection objects that communicate with each other 3
What is procedural Approach? In Procedural approach (procedural programming) code is organised into small "procedures that use and change the data. linear programming: One thing happens and then the next. Code is executed one after the other. Functions take some input. Function Processes the input. Function produce some output. 4
What is OOP? Object-oriented programming (OOP): A type of programming in which programmers define not only the attributes, but also the types of operations that can be applied to the data structure. In this way, the application becomes a set of objects that includes both data and functions. 5
Object-oriented programming (OOP) Object-Oriented Combines data and behavior into one unit objects Provides Data abstraction and encapsulation Decompose program into objects. Programs are collections of interacting and cooperating objects. Essential for large programs Analyze program requirements, then develop 6
Class & Object 7
Example: Class ELibarary 8
Object Oriented Programming In object-oriented programming, classes are used to group related variables and methods. A class is a collection of a fixed number of components (members). Class creates objects. The data inside an object can only be manipulated by calling the object's methods. Data is locked inside object. Methods are the only way to access data. 9
Java Class Libraries Classes Include methods that perform tasks Return information after task completion Used to build Java programs Java provides class libraries Known as Java APIs (Application Programming Interfaces) 10
Definition of Class Classes are constructs that define objects of the same type. A Java class describes data (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. 11
About Objects Objects Reusable software components that model real-world items Look all around you People, animals, plants, cars, etc. Each object has attributes and its own behavior. Attributes Size, shape, color, weight, etc. Behaviors Babies cry, sleep, etc. 12
About Objects An attribute: is characteristic of an object. It describes the kinds of information that an object needs in order to provide the required behaviors. So a patient object might have attributes such as condition, date admitted, medication and so on. The attribute value of condition might be malaria and the attribute value of date admitted might be 3/1/2006. The behavior of an object: is the collection of actions an object knows how to carry out. The values of all an object s attribute together determine the object s state. 13
Diagram of program structure 14
To build class A new class will be considered as a new data type, so you can declare a variables (Objects) of them and then you can set and get data to its properties. 15
Example 1 1 // Fig. 3.1: GradeBook.java 2 // Class declaration with one method. 3 4 public class GradeBook 5 { 6 // display a welcome message to the GradeBook user 7 public void displaymessage() Print line of text to output 8 { 9 System.out.println( "Welcome to the Grade Book!" ); 10 } // end method displaymessage 11 12 } // end class GradeBook 16
Example 1 1 // Fig. 3.2: GradeBookTest.java 2 // Create a GradeBook object and call its displaymessage method. 3 4 public class GradeBookTest 5 { 6 // main method begins program execution 7 public static void main( String args[] ) 8 { 9 // create a GradeBook object and assign it to mygradebook 10 GradeBook mygradebook = new GradeBook(); 11 12 // call mygradebook's displaymessage method 13 mygradebook.displaymessage(); 14 } // end main 15 16 } // end class GradeBookTest Use class instance creation expression to create object of class GradeBook Call method displaymessage using GradeBook object Welcome to the Grade Book! 17
Classes, Objects, Methods and Instance Variables Create a new class (GradeBook) Use it to create an object Each class declaration that begins with keyword public must be stored in a file that has the same name as the class and ends with the.java file-name extension. Keyword public is an access modifier. Indicates that the class is available to the public Class declarations include: Access modifier Keyword class Pair of left and right braces 18
Declaring a Class with a Method and Instantiating an Object of a Class Class GradeBook is not an application because it does not contain main. Can t execute GradeBook; will receive an error message. Must either declare a separate class that contains a main method or place a main method in class GradeBook. 19
Declaring a Class with a Method and Instantiating an Object of a Class 20
Class GradeBookTest Java is extensible Programmers can create new classes Class instance creation expression Keyword new creates new object of the class specified to the right of the keyword. Then name of class to create and parentheses. Calling a method Object name, then dot separator (.) Then method name and parentheses 21
UML class diagram for Class GradeBook Top compartment contains name of the class. Middle compartment contains class s attributes or instance variables Bottom compartment contains class s operations or methods Plus sign indicates public methods Fig. 7.3 UML class diagram indicating that class GradeBook has a public displaymessage operation. 22
Initializing Objects with Constructors Another definition of constructors: is a piece of code for initializing the state of an object of a class when it is created. The constructor is a method will have the same name of the class, and each class has at least one constructor. Called when keyword new is followed by the class name and parentheses Initialize an object of a class Java requires a constructor for every class Java will provide a default no-argument constructor if none is provided 23
Constructors A class may be declared without constructors. In this case, a no-argument 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. 24
Constructors - Example 25
Example 2 Example 2 26
Overloaded Constructors Overloaded constructors Provide multiple constructor definitions with different signatures No-argument constructor A constructor invoked without arguments 27
Access methods While properties should be private, so we need to available using them through methods, which called access methods Attributes(private instance variables) Cannot be accessed directly by clients of the object Use set methods to alter the value Use get methods to retrieve the value 28
Instance Variables, set Methods and get Methods Variables declared in the body of method Called local variables Can only be used within that method Variables declared in a class declaration Called fields or instance variables Each object of the class has a separate instance of the variable 29
Example 3 30
Example 3 31
1 // Fig. 3.7: GradeBook.java 2 // GradeBook class that contains a coursename instance variable 3 // and methods to set and get its value. 4 5 public class GradeBook Example 3 6 { 7 private String coursename; // course name for this GradeBook 8 9 // method to set the course name 10 public void setcoursename( String name ) 11 { 12 coursename = name; // store the course name 13 } // end method setcoursename 14 15 // method to retrieve the course name 16 public String getcoursename() 17 { 18 return coursename; 19 } // end method getcoursename 20 21 // display a welcome message to the GradeBook user 22 public void displaymessage() 23 { 24 // this statement calls getcoursename to get the 25 // name of the course this GradeBook represents 26 System.out.printf( "Welcome to the grade book for\n%s!\n", 27 getcoursename() ); 28 } // end method displaymessage 29 30 } // end class GradeBook Instance variable coursename set method for coursename get method for coursename Call get method Example 4 32
1 // Fig. 3.8: GradeBookTest.java 2 // Create and manipulate a GradeBook object. 3 import java.util.scanner; // program uses Scanner 4 5 public class GradeBookTest 6 { 7 // main method begins program execution 8 public static void main( String args[] ) 9 { 10 // create Scanner to obtain input from command window 11 Scanner input = new Scanner( System.in ); 12 13 // create a GradeBook object and assign it to mygradebook 14 GradeBook mygradebook = new GradeBook(); 15 16 // display initial value of coursename 17 System.out.printf( "Initial course name is: %s\n\n", 18 mygradebook.getcoursename() ); 19 Call get method for coursename Example 4 33
20 // prompt for and read course name 21 System.out.println( "Please enter the course name:" ); 22 String thename = input.nextline(); // read a line of text 23 mygradebook.setcoursename( thename ); // set the course name 24 System.out.println(); // outputs a blank line 25 26 // display welcome message after specifying course name 27 mygradebook.displaymessage(); 28 } // end main 29 30 } // end class GradeBookTest Call set method for coursename Call displaymessage Example 4 Initial course name is: null Please enter the course name: CS101 Introduction to Java Programming Welcome to the grade book for CS101 Introduction to Java Programming! 34
GradeBook s UML Class Diagram with an Instance Variable and set and get Methods Attributes Listed in middle compartment Attribute name followed by colon followed by attribute type Return type of a method Indicated with a colon and return type after the parentheses after the operation name Fig. 7.9 UML class diagram indicating that class GradeBook has a coursename attribute of UML type String and three operations setcoursename (with a name parameter of UML type String), getcoursename (returns UML type String) and displaymessage. 35
Access modifier Access modifier: tells the Java compiler if other objects could access or invoke the corresponding class member. In this chapter, we will discuss 2 access modifiers: private: class members are accessible (visible) only inside the class, i.e. instances of other classes cannot directly access those members. If a member of a class is an attribute (instance variable) it is declared as follows: Access modifier data type attribute name; (E.g. private int position;) private keyword used for most instance variables public: class members are accessible inside and outside the class, i.e. visible to all classes. Instance variables are usually declared as private 36
Access Modifiers public and private private keyword used for most instance variables private variables and methods are accessible only to methods of the class in which they are declared Declaring instance variables private is known as data hiding Public variables and methods are accessible from outside the class. 37
My first class class Rectangle { public float length; public float width; public float area; Attributes(properties, instance variables) of rectangle class public Rectangle(){ length = 1.0f; width = 1.0f; area = recarea(); } Default Constructor of class It just gives any values to properties public Rectangle(float l, float w){ length = l; width = w; area = recarea(); } Overloaded constructor of class It gives values to properties by user } public float recarea(){ return length*width; } Method to calculate the area of rectangle Any rectangle has an area behavior 38
Example 5 1 // Fig. 3.4: GradeBook.java 2 // Class declaration with a method that has a parameter. 3 4 public class GradeBook 5 { 6 // display a welcome message to the GradeBook user 7 public void displaymessage( String coursename ) 8 { 9 System.out.printf( "Welcome to the grade book for\n%s!\n", 10 coursename ); 11 } // end method displaymessage 12 13 } // end class GradeBook Call printf method with coursename argument 39
1 // Fig. 3.5: GradeBookTest.java 2 // Create GradeBook object and pass a String to 3 // its displaymessage method. 4 import java.util.scanner; // program uses Scanner 5 6 public class GradeBookTest 7 { Example 3 8 // main method begins program execution 9 public static void main( String args[] ) 10 { 11 // create Scanner to obtain input from command window 12 Scanner input = new Scanner( System.in ); 13 14 // create a GradeBook object and assign it to mygradebook 15 GradeBook mygradebook = new GradeBook(); 16 17 // prompt for and input course name 18 System.out.println( "Please enter the course name:" ); 19 String nameofcourse = input.nextline(); // read a line of text 20 System.out.println(); // outputs a blank line 21 22 // call mygradebook's displaymessage method 23 // and pass nameofcourse as an argument 24 mygradebook.displaymessage( nameofcourse ); 25 } // end main 26 27 } // end class GradeBookTest Please enter the course name: CS101 Introduction to Java Programming Welcome to the grade book for CS101 Introduction to Java Programming! Call nextline method to read a line of input Call displaymessage with an argument 40
OOP Main concepts in OOP: Abstraction Encapsulation Inheritance Polymorphism 41
Abstraction and Encapsulation Class abstraction means to separate class implementation from the use of the class. The creator of the class provides a description of the class and let the user know how the class can be used. The user of the class does not need to know how the class is implemented. The detail of implementation is encapsulated and hidden from the user. 42
Abstraction and Encapsulation Class Encapsulation Units (classes) normally hide the details of their implementation from their clients. 43
Primitive Types vs. Reference Types Types in Java: Primitive : boolean, byte, char, short, int, long, float, double Reference (sometimes called nonprimitive types): Objects Used to invoke an object s methods Reference type variables are variables which are declared to hold objects. The word reference, means the reserved memory location for this variable will not hold object itself but it will hold reference (address) to where the object is stored in memory 44
Primitive Types vs. Reference Types Similarities and differences between value type variables & reference type variables: Reference type variables are declared in the same way as value type variables. The values of primitive data types (e.g. 42, 12.4 or d ) are predefined; they already exist. They are built into the language. You just use them. In contrast, objects have to be created as required. You can create as many objects of a class as you want while any primitive data type has a finite number of values. A programmer can invent new classes of objects. It is not possible to make new primitive data types in Java. Objects usually take up much more memory than values of primitive data types. 45
Referring to the Current Object s Members with the this Reference The this reference Any object can access a reference to itself with keyword this classللوصول لعناصر ال thisتستخدم Non-static methods implicitly use this when referring to the object s instance variables and other methods Can be used to access instance variables when they are shadowed by local variables or method parameters 46
Example 6 Example 6 47
Example 6 Example 6 48
References: There are some slides from the lectures of 1- Dr. Hikmat Jabir 2- Dr. Bayan Abu Shawar 3- lecturer Mohamed Alfara 4- Dr. Fatimah rayan 49