Presentation is loading. Please wait.

Presentation is loading. Please wait.

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Chapter 2 OOP Characteristics.

Similar presentations


Presentation on theme: "Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Chapter 2 OOP Characteristics."— Presentation transcript:

1 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Chapter 2 OOP Characteristics F Class F Objects F Characteristics of OOP F Methods F Constructor F packages 4.1

2 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 1. What is a Class? F A 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 L 4.3

3 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Class Definition F A class contains a name, several variable declarations (instance variables) and several method declarations. F All are called members of the class. F 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) { … } } L 4.7

4 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Class F Class is a set of attributes and operations/ methods that are performed on the attributes. F A class represents a template for several objects that have common properties. F A class is sometimes called the object’s type. 4 Account accountName accountBalance withdraw() deposit() determineBalance() Student name age studentId getName() getId() Circle centre radius area() circumference()

5 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 2. What is an Object? F An Object Oriented system is a collection of interacting Objects. F Object is an instance of a class. F Real world objects are things that have: 1) state 2) behavior Example: your dog: الكلب F state – name, color, breed, sits?, barks?, wages tail?, runs? الدولة _ اسم أو اللون أو السلالة، يجلس، ينبح، والأجور الذيل، ويدير F behavior – sitting, barking, waging tail, running F السلوك _ الجلوس، وينبح، شن الذيل، تشغيل F A software object is a bundle of variables (state) and methods (operations). L 4.2

6 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Object F Objects have state and classes don’t. John is an object (instance) of class Student. name = “John”, age = 20, studentId = 1236 Jill is an object (instance) of class Student. name = “Jill”, age = 22, studentId = 2345 circleA is an object (instance) of class Circle. centre = (20,10), radius = 25 circleB is an object (instance) of class Circle. centre = (0,0), radius = 10 6

7 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Object Creation F A 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(); L 4.4

8 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Classes: Objects with the same attributes and behavior 8

9 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Classes/Objects 9 Student :John :Jill John and Jill are objects of class Student Circle :circleA :circleB circleA and circleB are objects of class Circle

10 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 3. OOP Characteristics F Model the real world problem to user’s perceive; F Construct reusable components; F Create new components from existing ones. F نموذج مشكلة العالم الحقيقي لإدراك المستخدم؛ F بناء مكونات قابلة للاستخدام؛ F إنشاء مكونات جديدة من القائمة. 10

11 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Object Oriented Paradigm: Features 11 OOP Paradigm Encapsulation Multiple Inheritance Polymorphism Single Inheritance Data Abstraction Java

12 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Encapsulation It associates the code and the data it manipulates into a single unit; and keeps them safe from external interference and misuse. فإنه يقترن رمز والبيانات التي تعالج في وحدة واحدة، ويبقيهم في مأمن من التدخل الخارجي وسوء الاستخدام. 12 OOP Paradigm Encapsulation Multiple Inheritance Polymorphism Single Inheritance Data Abstraction Data Functions

13 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Encapsulation F 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 دعم الكائن معلومات إخفاء _ يمكن إخفاء بعض الصفات والأساليب من المستخدم. 13

14 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Encapsulation - Example 14 class Account { private String accountName; private double accountBalance; public withdraw(); public deposit(); public determineBalance(); } // Class Account Deposit Withdraw Determine Balance Account balance messa ge

15 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Data Abstraction The technique of creating new data types that are well suited to an application. It allows the creation of user defined data types, having the properties of built data types and a set of permitted operators. 15 OOP Paradigm Encapsulation Multiple Inheritance Polymorphism Single Inheritance Data Abstraction تقنية خلق أنواع البيانات الجديدة التي هي مناسبة تماما لتطبيق. لأنها تتيح إنشاء أنواع البيانات المعرفة من قبل المستخدم، وجود خصائص أنواع البيانات التي بنيت ومجموعة من مشغلي المسموح بها.

16 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Abstract Data Type (ADT) F A structure that contains both data and the actions to be performed on that data. F Class is an implementation of an Abstract Data Type. 16 class Account { private String accountName; private double accountBalance; public withdraw(); public deposit(); public determineBalance(); } // Class Account

17 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Inheritance F New data types (classes) can be defined as extensions to previously defined types. F أنواع البيانات الجديدة (الطبقات) يمكن تعريفها على أنها ملحقات لأنواع المعرفة مسبقا. F Parent Class (Super Class) – Child Class (Sub Class) F Subclass inherits properties from the parent class. F فئة فرعية يرث الخصائص من الفئة الأصل 17 Parent Child Inherited capability

18 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Inheritance - Example 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, subjectID1, subjectID2) 18

19 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Inheritance - Example F Circle Class can be a subclass (inherited from ) of a parent class - Shape 19 Shape CircleRectangle

20 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 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. 20 Shape CircleRectangle GraphicCircle

21 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Uses of Inheritance – Multiple Inheritance F Inherit properties from more than one class. F This is called Multiple Inheritance. 21 Shape Circle Graphics

22 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 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. 22

23 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 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() area() method for rectangle will be executed. 23

24 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 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. 24

25 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 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

26 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 The Date Class F Java provides a system-independent encapsulation of date and time in the java.util.Date class. F 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. 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 2003.

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

28 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:  The following declaration creates an Integer object which is a reference to an object with the integer value 40 Integer age = new Integer(40); F Wrapper classes may contain static methods that help manage the associated type –For example, the Integer class contains a method to convert digits stored in a String to an int value: num = Integer.parseInt(str); 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 Primitive Type Wrapper Class byteByte shortShort intInteger longLong floatFloat doubleDouble charCharacter booleanBoolean voidVoid

29 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 TypeMethod StringnextLine() BytenextByte() IntegernextInteger() DoublenextDouble()

30 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 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.nextLine(); System.out.println ("You entered: \"" + message + "\""); } ObjectMethod ClassPackage Dot Operator

31 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 ManipulationMethod length of stringlength() character at position ncharAt(int index) find substring: start m and end n-1substring(int m, int n) change to upper casetoUpperCase()

32 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 String Handling 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. F 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. F For example, in the statement System.out.println("This is a String, too"); the string "This is a String, too" is a String constant F Java defines one operator for String objects: +. F It is used to concatenate two strings. For example, this statement F String myString = "I" + " like " + "Java."; results in myString containing "I like Java." L 8.3

33 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 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 charAt( ). F // Demonstrating some String methods. class StringDemo2 { public static void main(String args[]) { String strOb1 = "First String"; String strOb2 = "Second String"; String strOb3 = strOb1; System.out.println("Length of strOb1: " + strOb1.length()); System.out.println ("Char at index 3 in strOb1: " + strOb1.charAt(3)); if(strOb1.equals(strOb2)) System.out.println("strOb1 == strOb2"); else System.out.println("strOb1 != strOb2"); if(strOb1.equals(strOb3)) System.out.println("strOb1 == strOb3"); else System.out.println("strOb1 != strOb3"); } This program generates the following output: Length of strOb1: 12 Char at index 3 in strOb1: s strOb1 != strOb2 strOb1 == strOb3 L 8.5

34 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 34 4. Introducing Methods A method is a collection of statements that are grouped together to perform an operation.

35 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 35 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 returnValueType is the data type of the value the method returns. If the method does not return a value, the returnValueType is the keyword void. For example, the returnValueType in the main method is void.

36 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 36 Calling Method. animation This program demonstrates calling a method max to return the largest of the int values

37 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 37 Trace Method Invocation i is now 5 animation j is now 2

38 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 38 Trace Method Invocation invoke max(i, j) animation invoke max(i, j) Pass the value of i to num1 Pass the value of j to num2

39 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 39 Trace Method Invocation declare variable result animation (num1 > num2) is true since num1 is 5 and num2 is 2

40 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 40 Trace Method Invocation result is now 5 animation return result, which is 5

41 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 41 Trace Method Invocation return max(i, j) and assign the return value to k animation Execute the print statement

42 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Accessing members using object F 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 MyCircle{ public static void main(String args[]) { final float pi = 3.14f; Circle c = new Circle(); Scanner sc=new Scanner(System.in); System.out.print("Enter radius : "); c.radius = sc.nextInt(); c.perimeter = 2.0f * 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 42

43 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 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.nextInt(); } void calculate(){ final float pi = 3.14f; perimeter = 2.0f * pi * (float) radius; area = pi * (float) (radius * radius); System.out.println("Perimeter : "+ perimeter); System.out.println("Area : "+ area); } class OurCircle { public static void main(String args[]){ Circle c = new Circle(); c.input(); c.calculate(); } Output: Enter radius : 23 Perimeter : 144.44 Area : 1661.06 43

44 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 44 The Math Class F Class methods: –Trigonometric Methods –Exponent Methods –Rounding Methods –min, max, abs, and random Methods

45 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 45 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 toRadians(90) 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

46 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 46 Exponent Methods  exp(double a) Returns e raised to the power of a.  log(double a) Returns the natural logarithm of a.  log10(double a) Returns the 10-based logarithm of a.  pow(double a, double b) Returns a raised to the power of b.  sqrt(double a) Returns the square root of a. Examples: 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

47 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 47 Rounding Methods  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  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  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  int round(float x) Return (int)Math.floor(x+0.5). Math.round(2.0) returns 2  long round(double x) Return (long)Math.floor(x+0.5). Math.round(-2.6) returns -3

48 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 48 min, max, and abs  max(a, b) and min(a, b) Returns the maximum or minimum of two parameters.  abs(a) Returns the absolute value of the parameter.  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

49 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 //Find min and max number using methods import java.util.Scanner; class Number{ int max(int x,int y) { if(x>y) return(x); else return(y); } int min(int x,int y) { if (x<y) return(x); else return(y); }} class MaxMin { public static void main(String args[]) { int a,b; int mx,mn; Number n = new Number(); Scanner sc = new Scanner(System.in); System.out.println("enter the first number"); a = sc.nextInt(); System.out.println("enter the second number"); b = sc.nextInt(); mx = n.max(a,b); System.out.println("maximum is "+mx); mn = n.min(a,b); System.out.println("minimum number is "+mn); }} 49

50 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 50 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,

51 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 5. Constructor F A constructor with no parameters is referred to as a no-arg constructor. F Constructors must have the same name as the class itself similar to a method. F Once defined, the constructor is automatically called immediately after the object is created, before the new operator completes. F Constructors do not have a return type—not even void. This is because the implicit return type of a class constructor is the class type itself. Let’s examine the constructor included for the class ‘Country’. class Country { long population; int noOfStates; float currancyRate; Country(long x, int y) { population = x;noOfStates = y; } void display() { System.out.println(“Population:”+popu lation); System.out.println(“No of states:”+noOfStates); }} 51

52 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All 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 BoxClass{ public static void main(String args[]) { Box a = new Box(); //statement1 System.out.println("depth of a : "+a.depth); Box b = new Box(12,23); //statement2 System.out.println("depth of b : "+b.depth); Box c = new Box(99,84,36); //statement3 System.out.println("depth of c : "+c.depth); } 52

53 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 53 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. F Observe the following code, // without this keyword public class Point { public int x = 0; public int y = 0; //constructor public Point(int a, int b) { x = a; y = b; } // with this keyword public class Point { public int x = 0; public int y = 0; //constructor public Point(int x, int y) { this.x = x; this.y = y; }

54 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 //Without this keyword class Student{ int id; String name; Student(int id,String name){ id = id; name = name; } void display(){System.out.println(id+" "+ name);} public static void main(String args[]){ Student s1 = new student(111," Ali "); Student s2 = new student(321," Umar "); s1.display(); s2.display(); } Output:0 null 0 null //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 s1 = new Student(111,”Ali"); Student s2 = new Student(222,“Akber"); s1.display(); s2.display(); } Output:111 Ali 222 Akber 54

55 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 // constructor overloading using This keyword class Student{ int id; String name; String city; Student(int id,String name) { this.id = id; this.name = name; } Student(int id,String name,String city) { this(id,name); //now no need to initialize id and name this.city=city; } void display() { System.out.println(id+" "+name+" "+city); } public static void main(String args[]){ Student e1 = new Student(111,”Ali"); Student e2 = new Student(222,“Akber", “saudi"); e1.display(); e2.display(); } Output: 111 Ali null 222 Akber saudi 55

56 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Static Members F Methods and variables defined inside the class are called as instance methods and instance variables. F When a number of objects are created from the same class, each instance has its own copy of class variables. F But this is not the case when it is declared as static static. F That is, the member belongs to the class as a whole rather than the objects created from the class. F 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 They can only call other static methods. F They must only access static data. F They cannot refer to this or super in any way. 56

57 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 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 s1 = new Student (111,"Karan"); Student s2 = new Student (222,"Aryan"); s1.display(); s2.display(); } } Output:111 Karan ITS 222 Aryan ITS 57

58 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 //Demonstration of static members class MyWork{ static int x = 10; static int count = 1; static void display() { System.out.println("Static has initialized..."); } static void increment() { System.out.println("Function call : "+count); count++; } class StaticMember{ public static void main(String args[]) { MyWork.display(); //statement1 System.out.print("Value of x: "); System.out.println(MyWork.x); //statement2 MyWork.increment(); //statement3 MyWork.increment(); //statement4 MyWork.increment(); //statement5 } Output: Static has initialized... Value of x: 10 Function call : 1 Function call : 2 Function call : 3 58

59 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Argument passing to methods F There are two ways that a programming language can pass an argument to a function. 1. call-by-value: This method copies the value of an argument into the formal parameter of the function. Therefore, changes made to the parameter of the function have no effect on the argument. 2. call-by-reference. In this method, a reference to an argument (not the value of the argument) is passed to the parameter. Changes made to the parameter will affect the argument used to call the function. Example of Call by Value class Test{ void meth(int i, int j){ i++; j++; } class CallByValue{ public static void main(String args[]) { Test ob = new Test(); int a = 22, b = 93; System.out.print("a and b before call: "); System.out.println(a + " " + b); ob.meth(a, b); System.out.print("a and b after call: "); System.out.println(a + " " + b); } Output: a and b before call: 22 93 a and b after call: 22 93 59

60 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All 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 CallByRef { 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 60

61 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 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 ReturnObject { (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 61

62 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 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. 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 InnerClass{ (1)public static void main(String args[]){ (2) Outer outer = new Outer(15); (5)outer.test(); } } Output: Value: outx =15 62

63 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 63 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.

64 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 64 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 –package packagename; –If not, the class is in a default unnamed package

65 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 65 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.

66 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 66 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.

67 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 67 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:\mysource\com\prenhall\mypackage. 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:\myclass\com\prenhall\mypackage.

68 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 68 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: package packagename; package startjava; //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System.out.println(“Welcome to Java!"); }

69 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 69 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, numOfDecimalDigits) 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:\book\com\prenhall\mypackage. // Format.java: Format number. package com.prenhall.mypackage; public class Format { public static double format( double number, int numOfDecimalDigits) { return Math.round(number * Math.pow(10, numOfDecimalDigits)) / Math.pow(10, numOfDecimalDigits); } 2. Compile Format.java. Make sure Format.class is in c:\book\com\prenhall\mypackage.

70 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 70 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. For 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.nextLine(); System.out.println("Welcome to Java! "+name); }

71 Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 71 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


Download ppt "Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 Chapter 2 OOP Characteristics."

Similar presentations


Ads by Google