Download Chapter2 oop characteristics

Document related concepts
no text concepts found
Transcript
Chapter 2
OOP Characteristics
 Class
 Objects
 Characteristics
of OOP
 Methods
 Constructor
 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?
A
class defines the variables and methods common
to all objects of a certain kind.
 Example: ‘your dog’ is a object of the class Dog.
 An object holds values for the variables defines in
the class.
 An object is called an instance of the Class
 Each concept we wish to describe in Java must be
included inside a class.
 A class defines a new data type, whose values are
objects:
 A class is a template for objects
 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



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



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
accountName
accountBalance
withdraw()
deposit()
determineBalance()
Student
Circle
name
age
studentId
getName()
getId()
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?







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

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
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
6
Object Creation
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.)
 A new String object is created in memory with
initial “abc” value:
 String s = new String(“abc”);
 Now s contains the address of this new object.
 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
Person Objects
Abstract
Into
Person Class
Attributes: Name, Age, Sex
Operations: Speak(), Listen(), Walk()
Abstract
Into
Vehicle Class
Name, Model, Color
Attributes:
Operations: Start(), Stop(), Accelerate()
Vehicle Objects
Polygon Objects
Abstract
Into
Polygon Class
Attributes: Vertices, Border,
Color,
FillColor
Operations: Draw(), Erase(), Move()
Figure 1.12:
Objects and classes
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
8
Classes/Objects
:John
Student
John and Jill are
objects of class
Student
:Jill
:circleA
Circle
:circleB
circleA and circleB
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;
 Construct reusable
components;
 Create new components
from existing ones.
‫ نموذج مشكلة العالم الحقيقي إلدراك‬
‫المستخدم؛‬
‫ بناء مكونات قابلة لالستخدام؛‬
.‫ إنشاء مكونات جديدة من القائمة‬

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
Encapsulation

Data Abstraction
Single Inheritance

OOP
Paradigm
Polymorphism
Multiple Inheritance
It associates the code and
the data it manipulates into
a single unit; and keeps
them safe from external
interference and misuse.
‫فإنه يقترن رمز والبيانات التي‬
‫ ويبقيهم في‬،‫تعالج في وحدة واحدة‬
‫مأمن من التدخل الخارجي وسوء‬
.‫االستخدام‬
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.
 Information can be manipulated through
operations performed on the object/class –
interface to the class. Implementation is hidden
from the user.‫مخفيا تنفيذ من قبل المستخدم‬
 Object support Information Hiding – Some
attributes and methods can be hidden from the
user.
‫ دعم الكائن معلومات إخفاء _ يمكن إخفاء بعض الصفات‬
.‫واألساليب من المستخدم‬

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 accountName;
private double accountBalance;
message
Withdraw
public withdraw();
public deposit();
public determineBalance();
} // Class Account
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.

.‫تقنية خلق أنواع البيانات الجديدة التي هي مناسبة تماما لتطبيق‬
‫ وجود‬،‫ألنها تتيح إنشاء أنواع البيانات المعرفة من قبل المستخدم‬
‫خصائص أنواع البيانات التي بنيت ومجموعة من مشغلي المسموح‬
.‫ بها‬15
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Abstract Data Type (ADT)


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 accountName;
private double accountBalance;
public withdraw();
public deposit();
public determineBalance();
} // Class Account
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
16
Inheritance
 New
data types (classes) can be defined as
extensions to previously defined types.
‫ أنواع البيانات الجديدة (الطبقات) يمكن تعريفها على أنها‬
.‫ملحقات ألنواع المعرفة مسبقا‬
 Parent Class (Super Class) –
Parent
Child Class (Sub Class)
Inherited
 Subclass inherits properties from the
capability
parent class.

‫فئة فرعية يرث الخصائص من الفئة األصل‬
Child
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
17
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)
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
18
Inheritance - Example

Circle Class can be a subclass (inherited from ) of a
parent class - Shape
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

Inheritance can also have
multiple levels.

If multiple classes have
common attributes/methods,
these methods can be moved to
a common class - parent class.

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
GraphicCircle
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
 Inherit
properties from more than one class.
 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

Polymorphic which means “many forms” has
Greek roots.
– Poly – many
– Morphos - forms.

In OO paradigm polymorphism has many forms.

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

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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
23
Polymorphism – Method Overloading
 Multiple
methods can be defined with the
same name, different input arguments.
Method 1 - initialize(int a)
Method 2 - initialize(int a, int b)
 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


Java provides a system-independent encapsulation of date and time in
the java.util.Date class.
You can use the Date class to create an instance for the current date
and time and use its toString method to return the date and time as a
string.
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.
The + sign indicates
public modifer
java.util.Date
+Date()
Constructs a Date object for the current time.
+Date(elapseTime: long)
Constructs a Date object for a given time in
milliseconds elapsed since January 1, 1970, GMT.
+toString(): String
Returns a string representing the date and time.
+getTime(): long
Returns the number of milliseconds since January 1,
1970, GMT.
+setTime(elapseTime: long): void Sets a new elapse time in the object.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
The Random Class

You have used Math.random() to obtain a random double
value between 0.0 and 1.0 (excluding 1.0). A more useful
random number generator is provided in the java.util.Random
class.
java.util.Random
+Random()
Constructs a Random object with the current time as its seed.
+Random(seed: long)
Constructs a Random object with a specified seed.
+nextInt(): int
Returns a random int value.
+nextInt(n: int): int
Returns a random int value between 0 and n (exclusive).
+nextLong(): long
Returns a random long value.
+nextDouble(): double
Returns a random double value between 0.0 and 1.0 (exclusive).
+nextFloat(): float
Returns a random float value between 0.0F and 1.0F (exclusive).
+nextBoolean(): boolean
Returns a random boolean value.
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 Primitive
Wrapper
Integer age = new Integer(40);
Type
Class
Byte
 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.parseInt(str);


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
nextLine()
Byte
nextByte()
Integer
nextInteger()
Double
nextDouble()
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.nextLine();
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
charAt(int index)
find substring: start m and end n-1
substring(int m, int n)
change to upper case
toUpperCase()
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
String Handling






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 myString = "I" + " like " + "Java.";
results in myString 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 charAt( ).
 // 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
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.
Define a method
modifier
method
header
return value type
Invoke a method
method name
formal parameters
public static int max(int num1, int num2) {
int z = max(x, y);
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
parameter list
actual parameters
(arguments)
return value
return result;
}
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 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.
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
pass the value of i
pass the value of j
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}
return result;
}
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)
invoke max(i, j)
Pass the value of i to num1
Pass the value of j to num2
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
(num1 > num2) is true since num1
is 5 and num2 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 object
objectname.variablename
 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
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.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
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
43
The Math Class
 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

sin(double a)

cos(double a)

tan(double a)

acos(double a)

asin(double a)

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
toRadians(90)
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
45
Exponent Methods

exp(double a)
Returns e raised to the power of a.
Examples:

log(double a)
Returns the natural logarithm of a.

log10(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.

pow(double a, double b)
Returns a raised to the power of b.

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

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
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
47
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
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;
{
class Number{
int a,b;
int max(int x,int y)
int mx,mn;
{
Number n = new Number();
if(x>y)
Scanner sc = new Scanner(System.in);
return(x);
System.out.println("enter the first
number");
else
a = sc.nextInt();
return(y);
System.out.println("enter the second
}
number");
int min(int x,int y)
b = sc.nextInt();
{
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 MaxMin
}}
{
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:
(int)(Math.random() * 10)
Returns a random integer
between 0 and 9.
50 + (int)(Math.random() * 50)
Returns a random integer
between 50 and 99.
In general,
a + Math.random() * b
Returns a random number between
a and a + b, excluding a + b.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
50
5. Constructor
class Country
{
 Constructors must have the same name long population;
as the class itself similar to a method. int noOfStates;
float currancyRate;
 Once defined, the constructor is
automatically called immediately after Country(long x, int y)
the object is created, before the new {
operator completes.
population = x;noOfStates = y;
 Constructors do not have a return
}
type—not even void. This is because void display()
the implicit return type of a class
{
constructor is the class type itself.
System.out.println(“Population:”+popu
Let’s examine the constructor included for
lation);
the class ‘Country’.
System.out.println(“No of
states:”+noOfStates);
}}

A constructor with no parameters is
referred to as a no-arg constructor.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
51
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);
}
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
52
The this Keyword

Use this to refer to the object that invokes the instance method.

Use this to refer to an instance data field.

Use this to invoke an overloaded constructor of the same class.

Observe the following code,
// with this keyword
// without this keyword
public class Point {
public class Point {
public int x = 0;
public int x = 0;
public int y = 0;
public int y = 0;
//constructor public
//constructor public
Point(int x, int y)
Point(int a, int b)
{
{
this.x = x;
x = a;
this.y = y;
y = b;
}
}
}
}
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{
class Student{
int id;
int id;
String name;
String name;
Student(int id,String name){
Student(int id,String name){
id = id;
this.id = id;
name = name;
this.name = name;
}
}
void display(){System.out.println(id+" "+ void display(){System.out.println(id+" "+
name);}
name);}
public static void main(String args[]){
public static void main(String args[]){
Student s1 = new student(111," Ali ");
Student s1 = new Student(111,”Ali");
Student s2 = new student(321," Umar ");
Student s2 = new Student(222,“Akber");
s1.display();
s1.display();
s2.display();
s2.display();
}
}
}
}
Output:0 null 0 null
Output:111 Ali 222 Akber
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
54
// constructor overloading using This
void display()
keyword
{
class Student{
System.out.println(id+" "+name+" "+city);
int id;
}
String name;
public static void main(String args[]){
String city;
Student e1 = new Student(111,”Ali");
Student(int id,String name)
Student e2 = new Student(222,“Akber",
{
“saudi");
this.id = id;
e1.display();
this.name = name;
e2.display();
}
}
Student(int id,String name,String city)
}
{
Output:
this(id,name);
111 Ali null
//now no need to initialize id and name
222 Akber saudi
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





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 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:



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 s1 = new Student (111,"Karan");
Student s2 = new Student (222,"Aryan");
s1.display();
s2.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 MyWork{
MyWork.display(); //statement1
static int x = 10;
System.out.print("Value of x: ");
static int count = 1;
System.out.println(MyWork.x);
//statement2
static void display()
MyWork.increment();
{
//statement3
System.out.println("Static has
MyWork.increment();
initialized...");
//statement4
}
MyWork.increment();
static void increment()
//statement5
{
}
System.out.println("Function call :
}
"+count);
Output:
count++;
Static has initialized... Value of x: 10
}
Function call : 1
}
Function call : 2
class StaticMember {
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

There are two ways that a programming
}
language can pass an argument to a
class CallByValue{
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 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
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 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
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.
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
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.
 Everything in java is part of a class.
 Packages are used to group classes
 Package can contain other packages
 Java expects a one-to-one mapping of the package name and the
file system directory structure
 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
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:\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.
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:
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!");
}
}
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,
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.
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. 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);
}
}
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