Chapter 2 OOP Characteristics F Class F Objects
Chapter 2 OOP Characteristics F Class F Objects F Characteristics of OOP F Methods F Constructor F packages Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 4. 1
1. What is a Class? FA class defines the variables and methods common to all objects of a certain kind. F Example: ‘your dog’ is a object of the class Dog. F An object holds values for the variables defines in the class. F An object is called an instance of the Class F Each concept we wish to describe in Java must be included inside a class. F A class defines a new data type, whose values are objects: F A class is a template for objects F An object is an instance of a class Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 L 4. 3
Class Definition F F F A class contains a name, several variable declarations (instance variables) and several method declarations. All are called members of the class. General form of a class: class Classname { type instance-variable-1; … type instance-variable-n; type method-name-1(parameter-list) { … } type method-name-2(parameter-list) { … } … type method-name-m(parameter-list) { … } } Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 L 4. 7
Class F F F Class is a set of attributes and operations/ methods that are performed on the attributes. A class represents a template for several objects that have common properties. A class is sometimes called the object’s type. Account account. Name account. Balance withdraw() deposit() determine. Balance() Student Circle name age student. Id get. Name() get. Id() centre radius area() circumference() Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 4
2. What is an Object? F F F F An Object Oriented system is a collection of interacting Objects. Object is an instance of a class. Real world objects are things that have: 1) state 2) behavior Example: your dog: ﺍﻟﻜﻠﺐ state – name, color, breed, sits? , barks? , wages tail? , runs? ﺍﻟﺪﻭﻟﺔ _ ﺍﺳﻢ ﺃﻮ ﻭﻳﺪﻳﺮ ، ﻭﺍﻷﺠﻮﺭ ﺍﻟﺬﻳﻞ ، ﻳﻨﺒﺢ ، ﻳﺠﻠﺲ ، ﺍﻟﻠﻮﻥ ﺃﻮ ﺍﻟﺴﻼﻟﺔ behavior – sitting, barking, waging tail, running ﺗﺸﻐﻴﻞ ، ﺷﻦ ﺍﻟﺬﻳﻞ ، ﻭﻳﻨﺒﺢ ، ﺍﻟﺴﻠﻮﻙ _ ﺍﻟﺠﻠﻮﺱ A software object is a bundle of variables (state) and methods (operations). Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 L 4. 2
Object F Objects have state and classes don’t. John is an object (instance) of class Student. name = “John”, age = 20, student. Id = 1236 Jill is an object (instance) of class Student. name = “Jill”, age = 22, student. Id = 2345 circle. A is an object (instance) of class Circle. centre = (20, 10), radius = 25 circle. B is an object (instance) of class Circle. centre = (0, 0), radius = 10 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 6
FA Object Creation variable is declared to refer to the objects of type/class String: String s; (The value of s is null; it does not yet refer to any object. ) F A new String object is created in memory with initial “abc” value: F String s = new String(“abc”); F Now s contains the address of this new object. F Syntax for the Object : class_name object_name = new class_name(); Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 L 4. 4
Classes: Objects with the same attributes and behavior Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 8
Classes/Objects Student : John : Jill Circle : circle. A : circle. B John and Jill are objects of class Student circle. A and circle. B are objects of class Circle Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 9
3. OOP Characteristics Model the real world problem to user’s perceive; F Construct reusable components; F Create new components from existing ones. ﻧﻤﻮﺫﺝ ﻣﺸﻜﻠﺔ ﺍﻟﻌﺎﻟﻢ ﺍﻟﺤﻘﻴﻘﻲ ﻹﺩﺭﺍﻙ F ﺍﻟﻤﺴﺘﺨﺪﻡ؛ ﺑﻨﺎﺀ ﻣﻜﻮﻧﺎﺕ ﻗﺎﺑﻠﺔ ﻟﻼﺳﺘﺨﺪﺍﻡ؛ F. ﺇﻧﺸﺎﺀ ﻣﻜﻮﻧﺎﺕ ﺟﺪﻳﺪﺓ ﻣﻦ ﺍﻟﻘﺎﺋﻤﺔ F F Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 10
Object Oriented Paradigm: Features Encapsulation Data Abstraction Single Inheritance OOP Paradigm Polymorphism Java Multiple Inheritance Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 11
Encapsulation associates the code and the data it manipulates into a single unit; and keeps Data Abstraction them safe from external Single Inheritance interference and misuse. � ﻓﺈﻧﻪ ﻳﻘﺘﺮﻥ ﺭﻣﺰ ﻭﺍﻟﺒﻴﺎﻧﺎﺕ ﺍﻟﺘﻲ Polymorphism ﻭﻳﺒﻘﻴﻬﻢ ﻓﻲ ، ﺗﻌﺎﻟﺞ ﻓﻲ ﻭﺣﺪﺓ ﻭﺍﺣﺪﺓ ﻣﺄﻤﻦ ﻣﻦ ﺍﻟﺘﺪﺧﻞ ﺍﻟﺨﺎﺭﺟﻲ ﻭﺳﻮﺀ Multiple Inheritance. ﺍﻻﺳﺘﺨﺪﺍﻡ Encapsulation OOP Paradigm � It Data Functions Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 12
Encapsulation All information (attributes and methods) in an object oriented system are stored within the object/class. F Information can be manipulated through operations performed on the object/class – interface to the class. Implementation is hidden from the user. ﻣﺨﻔﻴﺎ ﺗﻨﻔﻴﺬ ﻣﻦ ﻗﺒﻞ ﺍﻟﻤﺴﺘﺨﺪﻡ F Object support Information Hiding – Some attributes and methods can be hidden from the user. ﺩﻋﻢ ﺍﻟﻜﺎﺋﻦ ﻣﻌﻠﻮﻣﺎﺕ ﺇﺧﻔﺎﺀ _ ﻳﻤﻜﻦ ﺇﺧﻔﺎﺀ ﺑﻌﺾ ﺍﻟﺼﻔﺎﺕ F. ﻭﺍﻷﺴﺎﻟﻴﺐ ﻣﻦ ﺍﻟﻤﺴﺘﺨﺪﻡ F Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 13
Encapsulation - Example class Account { private String account. Name; private double account. Balance; public withdraw(); public deposit(); public determine. Balance(); } // Class Account message Withdraw messa ge Deposit Account balance Determine Balance message Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 14
Data Abstraction Encapsulation OOP Paradigm � The technique of creating new data types Data Abstraction that are well suited to an application. Single Inheritance � It allows the creation of user defined data types, Polymorphism having the properties of built data types and a set Multiple Inheritance of permitted operators. . ﺗﻘﻨﻴﺔ ﺧﻠﻖ ﺃﻨﻮﺍﻉ ﺍﻟﺒﻴﺎﻧﺎﺕ ﺍﻟﺠﺪﻳﺪﺓ ﺍﻟﺘﻲ ﻫﻲ ﻣﻨﺎﺳﺒﺔ ﺗﻤﺎﻣﺎ ﻟﺘﻄﺒﻴﻖ ﻭﺟﻮﺩ ، ﻷﻨﻬﺎ ﺗﺘﻴﺢ ﺇﻧﺸﺎﺀ ﺃﻨﻮﺍﻉ ﺍﻟﺒﻴﺎﻧﺎﺕ ﺍﻟﻤﻌﺮﻓﺔ ﻣﻦ ﻗﺒﻞ ﺍﻟﻤﺴﺘﺨﺪﻡ . ﺧﺼﺎﺋﺺ ﺃﻨﻮﺍﻉ ﺍﻟﺒﻴﺎﻧﺎﺕ ﺍﻟﺘﻲ ﺑﻨﻴﺖ ﻭﻣﺠﻤﻮﻋﺔ ﻣﻦ ﻣﺸﻐﻠﻲ ﺍﻟﻤﺴﻤﻮﺡ ﺑﻬﺎ Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 15
Abstract Data Type (ADT) F F A structure that contains both data and the actions to be performed on that data. Class is an implementation of an Abstract Data Type. class Account { private String account. Name; private double account. Balance; public withdraw(); public deposit(); public determine. Balance(); } // Class Account Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 16
Inheritance F New data types (classes) can be defined as extensions to previously defined types. ﺃﻨﻮﺍﻉ ﺍﻟﺒﻴﺎﻧﺎﺕ ﺍﻟﺠﺪﻳﺪﺓ )ﺍﻟﻄﺒﻘﺎﺕ( ﻳﻤﻜﻦ ﺗﻌﺮﻳﻔﻬﺎ ﻋﻠﻰ ﺃﻨﻬﺎ F. ﻣﻠﺤﻘﺎﺕ ﻷﻨﻮﺍﻉ ﺍﻟﻤﻌﺮﻓﺔ ﻣﺴﺒﻘﺎ F Parent Class (Super Class) – Parent Child Class (Sub Class) Inherited F Subclass inherits properties from the capability parent class. F ﻓﺌﺔ ﻓﺮﻋﻴﺔ ﻳﺮﺙ ﺍﻟﺨﺼﺎﺋﺺ ﻣﻦ ﺍﻟﻔﺌﺔ ﺍﻷﺼﻞ Child Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 17
Inheritance - Example �Define Person to be a class �A Person has attributes, such as age, height, gender � Assign values to attributes when describing object �Define student to be a subclass of Person �A student has all attributes of Person, plus attributes of his/her own ( student no, course_enrolled) � A student inherits all attributes of Person �Define lecturer to be a subclass of Person � Lecturer has all attributes of Person, plus attributes of his/her own ( staff_id, subject. ID 1, subject. ID 2) Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 18
Inheritance - Example F Circle Class can be a subclass (inherited from ) of a parent class - Shape Circle Rectangle Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 19
Inheritance - Example F Inheritance can also have multiple levels. F If multiple classes have common attributes/methods, these methods can be moved to a common class - parent class. F This allows reuse since the implementation is not repeated. Example : Rectangle and Circle method have a common method move(), which requires changing the centre coordinate. Shape Circle Rectangle Graphic. Circle Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 20
Uses of Inheritance – Multiple Inheritance F Inherit properties from more than one class. F This is called Multiple Inheritance. Graphics Shape Circle Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 21
Polymorphism F Polymorphic which means “many forms” has Greek roots. – Poly – many – Morphos - forms. F In OO paradigm polymorphism has many forms. F Allow a single object, method, operator associated with different meaning depending on the type of data passed to it. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 22
Polymorphism F An object of type Circle or Rectangle can be assigned to a Shape object. The behavior of the object will depend on the object passed. Circle A = new Circle(); Create a new circle object Shape sh = A; sh. area(); area() method for circle class will be executed Rectangle A = new Rectangle(); Create a new rectangle object Shape sh= A; sh. area() method for rectangle will be executed. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 23
Polymorphism – Method Overloading F Multiple methods can be defined with the same name, different input arguments. Method 1 - initialize(int a) Method 2 - initialize(int a, int b) F Appropriate method will be called based on the input arguments. initialize(2) Method 1 will be called. initialize(2, 4) Method 2 will be called. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 24
Using Classes from the Java Library • • A class library is a set of classes that supports the development of programs. Java comes with a standard class library, but libraries can be obtained separately from third party vendors. Classes in class libraries contain methods that are valuable to the programmer. Classes are also grouped in packages. – Date Class – Random Class – Wrapper Class – Scanner Class – String Class Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6
The Date Class F F 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 to. String method to return the date and time as a string. For example, the following code java. util. Date date = new java. util. Date(); System. out. println(date. to. String()); displays a string like Sun Mar 09 13: 50: 19 EST 2003. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6
The Random Class F 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. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6
Wrapper class The java. lang package contains a wrapper class that corresponds to each primitive type: F The following declaration creates an Integer object which is a reference to an object with the integer value 40 Primitive Wrapper Integer age = new Integer(40); Type Class Byte F Wrapper classes may contain static methods that help byte short Short manage the associated type Integer – For example, the Integer class contains a methodint Long to convert digits stored in a String to an int value: long float Float num = Integer. parse. Int(str); F F Wrapper classes often contain useful constants – For example, the Integer class contains MIN_VALUE and MAX_VALUE for the smallest and largest int values double Double char Character boolean Boolean void Void Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6
Scanner Class • • • The Scanner class provides a convenient way to read input values of various types. The Scanner class accepts input from various sources including the keyboard, a file, or a string. Must be imported from java. util package For keyboard, use “System. in” in the constructor. See the chart below for a partial summary of available methods or appendix “M” for a complete list: Data Type Method String next. Line() Byte next. Byte() Integer next. Integer() Double next. Double() Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6
import java. util. Scanner; // First import the Scanner class Package Dot Operator Class public class Echo { //--------------------------------// Reads a character string from the user and prints it. //--------------------------------public static void main (String[] args) { String message; Scanner scan = new Scanner (System. in); System. out. println ("Enter a line of text: "); message = scan. next. Line(); System. out. println ("You entered: "" + message + """); } Object Method } Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6
String Class • • The String class provides a convenient way to manage and manipulate text. The String class is in the java. lang package and is automatically imported. String Manipulation Method length of string length() character at position n char. At(int index) find substring: start m and end n-1 substring(int m, int n) change to upper case to. Upper. Case() Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6
String Handling F F F String is probably the most commonly used class in Java's class library. The obvious reason for this is that strings are a very important part of programming. The first thing to understand about strings is that every string you create is actually an object of type String. Even string constants are actually String objects. For example, in the statement System. out. println("This is a String, too"); the string "This is a String, too" is a String constant Java defines one operator for String objects: +. It is used to concatenate two strings. For example, this statement String my. String = "I" + " like " + "Java. "; results in my. String containing "I like Java. " Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 L 8. 3
equals( ). You can obtain the length of a string by calling the length( ) method. You can obtain the character at a specified index within a string by calling char. At( ). F // Demonstrating some String methods. class String. Demo 2 { public static void main(String args[]) { String str. Ob 1 = "First String"; String str. Ob 2 = "Second String"; String str. Ob 3 = str. Ob 1; System. out. println("Length of str. Ob 1: " + str. Ob 1. length()); System. out. println ("Char at index 3 in str. Ob 1: " + str. Ob 1. char. At(3)); if(str. Ob 1. equals(str. Ob 2)) System. out. println("str. Ob 1 == str. Ob 2"); else System. out. println("str. Ob 1 != str. Ob 2"); if(str. Ob 1. equals(str. Ob 3)) System. out. println("str. Ob 1 == str. Ob 3"); else System. out. println("str. Ob 1 != str. Ob 3"); } } This program generates the following output: Length of str. Ob 1: 12 Char at index 3 in str. Ob 1: s str. Ob 1 != str. Ob 2 str. Ob 1 == str. Ob 3 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 L 8. 5
4. Introducing Methods A method is a collection of statements that are grouped together to perform an operation. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 34
Introducing Methods, cont. • Method signature is the combination of the method name and the parameter list. • The variables defined in the method header are known as formal parameters. • When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. • A method may return a value. The return. Value. Type is the data type of the value the method returns. If the method does not return a value, the return. Value. Type is the keyword void. For example, the return. Value. Type in the main method is void. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 35
animation Calling Method. This program demonstrates calling a method max to return the largest of the int values Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 36
animation Trace Method Invocation i is now 5 j is now 2 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 37
animation Trace Method Invocation invoke max(i, j) Pass the value of i to num 1 Pass the value of j to num 2 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 38
animation Trace Method Invocation declare variable result (num 1 > num 2) is true since num 1 is 5 and num 2 is 2 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 39
animation Trace Method Invocation result is now 5 return result, which is 5 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 40
animation Trace Method Invocation return max(i, j) and assign the return value to k Execute the print statement Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 41
Accessing members using objectname. variablename F The ‘objectname’ is the name of the object and ‘variablename’ is name of the instance variable. import java. util. Scanner; class Circle { int radius; float perimeter; float area; } class My. Circle{ public static void main(String args[]) { final float pi = 3. 14 f; Circle c = new Circle(); F Scanner sc=new Scanner(System. in); System. out. print("Enter radius : "); c. radius = sc. next. Int(); c. perimeter = 2. 0 f * pi * (float) c. radius; c. area=pi*(float)(c. radius*c. radius); System. out. println("Perimeter : "+c. perimeter); System. out. println("Area : "+c. area); } } Output: Enter radius : 23 Perimeter : 144. 44 Area : 1661. 06 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 42
Adding methods //Circle specifications using methods import java. util. Scanner; class Circle { int radius; float perimeter; float area; void input(){ Scanner in = new Scanner(System. in); System. out. print("Enter radius : "); radius = in. next. Int(); } void calculate(){ final float pi = 3. 14 f; perimeter = 2. 0 f * pi * (float) radius; area = pi * (float) (radius * radius); System. out. println("Perimeter : "+ perimeter); System. out. println("Area : "+ area); } } class Our. Circle { public static void main(String args[]){ Circle c = new Circle(); c. input(); c. calculate(); } } Output: Enter radius : 23 Perimeter : 144. 44 Area : 1661. 06 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 43
The Math Class F Class methods: – Trigonometric Methods – Exponent Methods – Rounding Methods – min, max, abs, and random Methods Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 44
Trigonometric Methods F sin(double a) F cos(double a) F tan(double a) F acos(double a) F asin(double a) F atan(double a) Radians Examples: Math. sin(0) returns 0. 0 Math. sin(Math. PI / 6) returns 0. 5 Math. sin(Math. PI / 2) returns 1. 0 Math. cos(0) returns 1. 0 Math. cos(Math. PI / 6) returns 0. 866 Math. cos(Math. PI / 2) returns 0 to. Radians(90) Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 45
Exponent Methods F exp(double a) Returns e raised to the power of a. Examples: F log(double a) Returns the natural logarithm of a. F log 10(double a) Math. exp(1) returns 2. 71 Math. log(2. 71) returns 1. 0 Math. pow(2, 3) returns 8. 0 Math. pow(3, 2) returns 9. 0 Math. pow(3. 5, 2. 5) returns 22. 91765 Math. sqrt(4) returns 2. 0 Math. sqrt(10. 5) returns 3. 24 Returns the 10 -based logarithm of a. F pow(double a, double b) Returns a raised to the power of b. F sqrt(double a) Returns the square root of a. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 46
Rounding Methods F double ceil(double x) x rounded up to its nearest integer. This integer is returned as a double value. Math. ceil(2. 1) returns 3. 0 F double floor(double x) x is rounded down to its nearest integer. This integer is returned as a double value. Math. floor(-2. 1) returns -3. 0 F double rint(double x) x is rounded to its nearest integer. If x is equally close to two integers, the even one is returned as a double. Math. rint(2. 5) returns 2. 0 F int round(float x) Return (int)Math. floor(x+0. 5). Math. round(2. 0) returns 2 F long round(double x) Return (long)Math. floor(x+0. 5). Math. round(-2. 6) returns -3 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 47
min, max, and abs F max(a, b)and min(a, b) Returns the maximum or minimum of two parameters. F abs(a) Returns the absolute value of the parameter. F random() Returns a random double value in the range [0. 0, 1. 0). Examples: Math. max(2, 3) returns 3 Math. max(2. 5, 3) returns 3. 0 Math. min(2. 5, 3. 6) returns 2. 5 Math. abs(-2) returns 2 Math. abs(-2. 1) returns 2. 1 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 48
//Find min and max number using methods public static void main(String args[]) { import java. util. Scanner; int a, b; class Number{ int mx, mn; int max(int x, int y) Number n = new Number(); { Scanner sc = new Scanner(System. in); if(x>y) System. out. println("enter the first return(x); number"); else a = sc. next. Int(); return(y); System. out. println("enter the second } number"); int min(int x, int y) b = sc. next. Int(); { mx = n. max(a, b); if (x<y) System. out. println("maximum is return(x); "+mx); else mn = n. min(a, b); return(y); System. out. println("minimum number }} is "+mn); class Max. Min }} { Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 49
The random Method Generates a random double value greater than or equal to 0. 0 and less than 1. 0 (0 <= Math. random() < 1. 0). Examples: In general, Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 50
5. Constructor F A constructor with no parameters is referred to as a no-arg constructor. class Country F Constructors must have the same name { as the class itself similar to a method. long population; int no. Of. States; F Once defined, the constructor is automatically called immediately after float currancy. Rate; the object is created, before the new Country(long x, int y) operator completes. { F Constructors do not have a return type population = x; no. Of. States = y; —not even void. This is because the } implicit return type of a class void display() constructor is the class type itself. { Let’s examine the constructor included for System. out. println(“Population: ”+popu the class ‘Country’. lation); System. out. println(“No of states: ”+no. Of. States); Liang, Introduction to Java Programming, Sixth Edition, }} (c) 2007 Pearson Education, Inc. All 51 rights reserved. 0 -13 -222158 -6
Constructor overloading The use of same name for different purposes. Class can have more than one constructor but with different parameters. This is known as constructor overloading. // Overloaded constructors class Box{ int height; int depth; int length; Box() { height = depth = length = 10; } Box(int x, int y) { height = x; depth = y; } Box(int x, int y, int z){ height = x; depth = y; length = z; } } class Box. Class{ public static void main(String args[]) { Box a = new Box(); //statement 1 System. out. println("depth of a : "+a. depth); Box b = new Box(12, 23); //statement 2 System. out. println("depth of b : "+b. depth); Box c = new Box(99, 84, 36); //statement 3 System. out. println("depth of c : "+c. depth); } } Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 52
The this Keyword F Use this to refer to the object that invokes the instance method. F Use this to refer to an instance data field. F Use this to invoke an overloaded constructor of the same class. Observe the following code, F // with this keyword // without this keyword public class Point { public int x = 0; public int y = 0; //constructor public Point(int a, int b) Point(int x, int y) { { x = a; this. x = x; y = b; this. y = y; } } Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 53
//Without this keyword //With this keyword class Student{ int id; String name; Student(int id, String name){ this. id = id; this. name = name; } } void display(){System. out. println(id+" "+ name); } public static void main(String args[]){ Student s 1 = new Student(111, ”Ali"); Student s 1 = new student(111, " Ali "); Student s 2 = new Student(222, “Akber"); Student s 2 = new student(321, " Umar "); s 1. display(); s 2. display(); } } Output: 111 Ali 222 Akber Output: 0 null Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 54
void display() // constructor overloading using This keyword { class Student{ System. out. println(id+" "+name+" "+city); int id; } String name; public static void main(String args[]){ String city; Student e 1 = new Student(111, ”Ali"); Student(int id, String name) Student e 2 = new Student(222, “Akber", “saudi"); { e 1. display(); this. id = id; e 2. display(); this. name = name; } } } Student(int id, String name, String city) Output: { 111 Ali null this(id, name); 222 Akber saudi //now no need to initialize id and name this. city=city; } Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 55
Static Members F F F Methods and variables defined inside the class are called as instance methods and instance variables. When a number of objects are created from the same class, each instance has its own copy of class variables. But this is not the case when it is declared as static. That is, the member belongs to the class as a whole rather than the objects created from the class. Such members can be created by preceding them with the keyword static. For example: static int cal=1; static void display(int x) Methods declared as static have several restrictions: F F F They can only call other static methods. They must only access static data. They cannot refer to this or super in any way. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 56
class Student{ int rollno; String name; static String college ="ITS"; Student(int r, String n){ rollno = r; name = n; } void display (){ System. out. println(rollno+" "+name+" "+college); } public static void main(String args[]){ Student s 1 = new Student (111, "Karan"); Student s 2 = new Student (222, "Aryan"); s 1. display(); s 2. display(); } } Output: 111 Karan ITS 222 Aryan ITS Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 57
//Demonstration of static members { class My. Work{ My. Work. display(); //statement 1 static int x = 10; System. out. print("Value of x: "); static int count = 1; System. out. println(My. Work. x); //statement 2 static void display() My. Work. increment(); { //statement 3 System. out. println("Static has My. Work. increment(); initialized. . . "); //statement 4 } My. Work. increment(); static void increment() //statement 5 { } System. out. println("Function call : } "+count); Output: count++; Static has initialized. . . Value of x: 10 } Function call : 1 } Function call : 2 class Static. Member { Function call : 3 public static void main(String Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All 58 rights reserved. 0 -13 -222158 -6 args[])
Argument passing to methods F } There are two ways that a programming language can pass an argument to a class Call. By. Value{ function. public static void main(String args[]) 1. call-by-value: This method copies the { value of an argument into the formal Test ob = new Test(); parameter of the function. Therefore, int a = 22, b = 93; changes made to the parameter of the function have no effect on the argument. System. out. print("a and b before call: "); System. out. println(a + " " + b); 2. call-by-reference. In this method, a reference to an argument (not the value of ob. meth(a, b); the argument) is passed to the parameter. System. out. print("a and b after call: "); Changes made to the parameter will affect System. out. println(a + " " + b); the argument used to call the function. } Example of Call by Value } class Test{ Output: void meth(int i, int j){ a and b before call: 22 93 i++; a and b after call: 22 93 j++; Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All 59 } rights reserved. 0 -13 -222158 -6
Example of Call by Reference // Objects are passed by reference. class Test { int a, b; void meth(Test o) { o. a++; o. b++; } } class Call. By. Ref { public static void main(String args[]) { Test ob = new Test(); ob. a = 22; ob. b = 93; System. out. println("ob. a and ob. b before call: " + ob. a + " " + ob. b); ob. meth(ob); System. out. println("ob. a and ob. b after call: " + ob. a + " " + ob. b); } } Output: ob. a and ob. b before call: 22 93 ob. a and ob. b after call: 23 94 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 60
Methods returning objects A method is able to return any type of the data. It can return the objects also. But in the method call the returning value of the method must be assigned to the object of that type. //A method returning object class Square { int n; (3)Square(int x) { (4)n = x; } (7)Square change() { (8)Square temp = new Square(n); (9)temp. n = temp. n * temp. n; (10)return(temp); } } class Return. Object { (1)public static void main(String[] args){ (2)Square s = new Square(8); (5)Square t; (6)t = s. change(); (11)System. out. println("Sqare of 8 is: "+t. n); } } Output: Square of 8 is: 64 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 61
Nested and inner classes There are two types of nested classes: static and non-static. A static nested class is one which has the static modifier applied. Because it is static, it must access the members of its enclosing class through an object. That is, it cannot refer to members of its enclosing class directly. Because of this restriction, static nested classes are rarely used. The most important type of nested class is the inner class. An inner class is a non-static nested class. It has access to all of the variables and methods of its outer class and may refer to them directly in the same way that other non-static members of the outer class do. Thus, an inner class is fully within the scope of its enclosing class. // Demonstration of an inner class Outer { //Outer class int outx; (3)Outer(int x) { (4)outx = x; } (6)void test(){ (7)Inner inner = new Inner(); (8)inner. display(); } } (9)class Inner { //Inner class (10)void display() { (11)System. out. print("Value: outx ="); (12)System. out. println(outx); }} } class Inner. Class{ (1)public static void main(String args[]) (2) Outer outer = new Outer(15); (5)outer. test(); } } Output: Value: outx =15 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 62
6. Package There are three reasons for using packages: 1. To avoid naming conflicts. When you develop reusable classes to be shared by other programmers, naming conflicts often occur. To prevent this, put your classes into packages so that they can be referenced through package names. 2. To distribute software conveniently. Packages group related classes so that they can be easily distributed. 3. To protect classes. Packages provide protection so that the protected members of the classes are accessible to the classes in the same package, but not to the external classes. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 63
Package-Naming Conventions Packages are hierarchical, and you can have packages within packages. For example, java. lang. Math indicates that Math is a class in the package lang and that lang is a package in the package java. Levels of nesting can be used to ensure the uniqueness of package names. F Everything in java is part of a class. F Packages are used to group classes F Package can contain other packages F Java expects a one-to-one mapping of the package name and the file system directory structure F Every class in Java belongs to a package, to put a class in a package, include this line as the first line – packagename; – If not, the class is in a default unnamed package Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 64
Package Directories Java expects one-to-one mapping of the package name and the file system directory structure. For the package named com. prenhall. mypackage, you must create a directory, as shown in the figure. In other words, a package is actually a directory that contains the bytecode of the classes. com. prenhall. mypackage The com directory does not have to be the root directory. In order for Java to know where your package is in the file system, you must modify the environment variable classpath so that it points to the directory in which your package resides. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 65
Setting classpath Environment The com directory does not have to be the root directory. In order for Java to know where your package is in the file system, you must modify the environment variable classpath so that it points to the directory in which your package resides. Suppose the com directory is under c: book. The following line adds c: book into the classpath: classpath=. ; c: book; The period (. ) indicating the current directory is always in classpath. The directory c: book is in classpath so that you can use the package com. prenhall. mypackage in the program. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 66
Setting Paths in JBuilder An IDE such as JBuilder uses the source directory path to specify where the source files are stored and uses the class directory path to specify where the compiled class files are stored. A source file must be stored in a package directory under the source directory path. For example, if the source directory is c: mysource and the package statement in the source code is package com. prenhall. mypackage, then the source code file must be stored in c: mysourcecomprenhallmypackage. A class file must be stored in a package directory under the class directory path. For example, if the class directory is c: myclass and the package statement in the source code is package com. prenhall. mypackage, then the class file must be stored in c: myclasscomprenhallmypackage. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 67
Putting Classes into Packages Every class in Java belongs to a package. The class is added to the package when it is compiled. All the classes that you have used so far in this book were placed in the current directory (a default package) when the Java source programs were compiled. To put a class in a specific package, you need to add the following line as the first noncomment and nonblank statement in the program: packagename; package startjava; //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System. out. println(“Welcome to Java!"); } } Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 68
Putting Classes into Packages Problem This example creates a class named Format and places it in the package com. prenhall. mypackage. The Format class contains the format(number, num. Of. Decimal. Digits) method that returns a new number with the specified number of digits after the decimal point. For example, format(10. 3422345, 2) returns 10. 34, and format(-0. 343434, 3) returns – 0. 343. Solution 1. Create Format. java as follows and save it into c: bookcomprenhallmypackage. // Format. java: Format number. package com. prenhall. mypackage; public class Format { public static double format( double number, int num. Of. Decimal. Digits) { return Math. round(number * Math. pow(10, num. Of. Decimal. Digits)) / Math. pow(10, num. Of. Decimal. Digits); } } 2. Compile Format. java. Make sure Format. class is in c: bookcomprenhallmypackage. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 69
Using Classes from Packages There are two ways to use classes from a package. • One way is to use the fully qualified name of the class. For example, the fully qualified name for Scanner class is java. util. Scanner. Format in the • The other way is to use the import statement. For example, to import all the classes in the java. util package, you can use import java. util. *; The import statement tells the compiler where to locate the classes. import java. util. Scanner; //This program prints Welcome to Java!+the name public class Welcome { public static void main(String[] args) { String name=""; Scanner scan = new Scanner(System. in); System. out. println("Enter your name: "); name=scan. next. Line(); System. out. println("Welcome to Java! "+name); } } Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 70
Using Classes from Packages Example of package that import the packagename. //save by A. java package pack; public class A{ public void msg(){ System. out. println("Hello"); } } //save by B. java package mypack; import pack. *; class B{ public static void main(String args[]){ A obj = new A(); obj. msg(); } } Output: Hello Example of package by import fully qualified name //save by A. java package pack; public class A{ public void msg(){ System. out. println("Hello"); } } //save by B. java package mypack; class B{ public static void main(String args[]) { pack. A obj = new pack. A(); obj. msg(); } } Output: Hello Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0 -13 -222158 -6 71
- Slides: 71