Sunteți pe pagina 1din 46

CLASSES AND OBJECTS - 1

OUTLINE OF THIS LECTURE


 Classes, Object variables, creating instance of a
class, constructors, instance/class variables,
instance/class methods
 4 useful Java classes:
 DecimalFormat

 Scanner

 Math

 GregorianCalendar

2
READING MATERIAL
 Chapter 3 Numerical Data
 Chapter 4 Defining Your Own Classes - Part 1

 Chapter 7 Defining Your Own Classes - Part 2

3
PRIMITIVE AND REFERENCE TYPES
Primitive types
 integers, real numbers, characters, boolean

Reference type
 String, BufferedReader, Scanner, …

In Java, all variables must be declared. A variable name


holds either a primitive value or a reference to an object.

int num = 5;
creates the variable num that holds the integer value 5.
String s = "How are you?";
creates the object variable s that holds a reference to the
4
String object "How are you?".
OBJECT VARIABLES - 1
 The declaration of object variables is similar to the
declaration of primitive variables. e.g.
String name;
 The class used to define an object can be thought of as the
type of an object.
 An object variable name holds the address of an object.
It is a pointer to the location in the memory where the
object is held.
With String name; the address stored in the object
variable name is 0 (null) as a String object has not been
created yet.

5
OBJECT VARIABLES - 2
To create or instantiate an object so that an object variable
can refer to it, we use new operator.
The new operator returns the address of the newly
created object.
Example:
name = new String(″John″);
The new operator is followed by the name of a special
method, called a constructor. The constructor helps to
set up an object.
Note:
A constructor has the same name as the class.
In the example, the parameter of the constructor is a string
literal that specifies the characters the string object will 6
hold.
OBJECT VARIABLES - 3
After an object is instantiated, the dot operator . is
used to access methods of the class from which the
object is instantiated
Example:
Scanner s = new Scanner(System.in);
int i = s.nextInt();

String str= new String(″John″); // or String str = ″John″


int len = str.length();

7
ASSIGNMENT IN PRIMITIVE TYPES
int i, j;
i = 5;
j = 6;
j = i;
// A copy of value in i is assigned to j.
// Both now contain the same value.

8
ASSIGNMENT IN REFERENCE TYPES
String n = ″narrow″;
String w = ″wide″;
// n and w refer to two different String objects.

9
ALIASES

When w = n; is executed
Given
 a copy of value in n is assigned to w.
String n = ″narrow″;
 n holds an address value which gets
String w = ″wide″; copied to w.
We have  Both n and w refer to the same object.

 n and w are now alias of each other.


n narrow

w narrow
wide n

w wide

Note that the reference to object ″wide″ is lost. It cannot be used 10


again. It is called garbage.
CLASSES
 We have been using Programs with single class
containing a main method, some other methods
and used methods of predefined classes from Java
class library.
 We can define our own classes to represent objects
found in a problem domain. e.g. Circle, Dice,
Equation, Triangle.

11
TEMPLATE FOR CLASS DEFINITION
Import Statements

Class Comment

class { Class Name

Data Members

Methods
(incl. Constructor)

12
DATA MEMBER DECLARATION
<modifiers> <data type> <name> ;

Modifiers Data Type Variable Name

public int radius;


Note: There’s only one modifier in this example.
It is a visibility modifier

13
CLASS CIRCLE
// no import statement as java.lang is imported automatically
// This class describes a circle
class Circle {
public int radius; // Data member
public Circle (int r) { // Constructor
radius = r;
}
}

14
INSTANTIATING AN OBJECT
// Test driver of class Circle
class TestCircle {
public static void main(string [] args) {
Circle c1 = new Circle(5);
Circle c2= new Circle(6);
}
}
 The new keyword is used to create (instantiate) an object of
class Circle. Object creation is also called object instantiation.
 Each object created is called an instance of the class.
 new will call the constructor to initialize the newly created
object. References to the objects are assigned to the variables
c1 and c2. 15
INSTANCE VARIABLE
 The data stored in each instance of a class is called
instance data. It is declared inside the class but not
inside any method.
 The variable radius is an instance variable of class
Circle. Every instance of class Circle will have this
data stored. It is also called an attribute of the class.
 Java automatically initializes instance variables with
0. However it is a good practice to initialize them
explicitly with specific values by a constructor.
 Instance variables of a class can be referenced in
any method of the class.
16
METHOD DECLARATION
<modifier> <return type> <method name> ( <parameters> ){
<statements>
}

Modifier Return Type Method Name Parameter

public void setOwnerName ( String name ) {

ownerName = name; Statements

}
17
CLASS BICYCLE
class Bicycle {
// Data Member
public String ownerName;
//Constructor: Initialzes the data member
public Bicycle( ) {
ownerName = "Unknown";
}
//Returns the name of this bicycle's owner
public String getOwnerName( ) {
return ownerName;
}
//Assigns the name of this bicycle's owner
public void setOwnerName(String name) {
ownerName = name;
}
} 18
SYNTAX OF A CONSTRUCTOR

public <class name> ( <parameters> ){


<statements>
}

Modifier Class Name Parameter

public Bicycle ( ) {
ownerName = "Unassigned";
} Statements
19
CONSTRUCTOR
 A constructor is a special method that will be
executed when an instance of the class is created.
 It is called via the new keyword.
 It includes statements for initializing data values.
 Its name is the name of the class.
 It does not have a return type (not even ″void″).
 Multiple constructors with different signatures are
allowed.
 For example, in class Bicycle, we can have one more
constructor as
public Bicycle(String owner) {
ownerName = owner;
20
}
CLASS BICYCLEREGISTRATION
// The test driver of class Bicycle
class BicycleRegistration {
public static void main(String[] args) {
Bicycle bike1, bike2;
String owner1, owner2;
bike1 = new Bicycle( ); // One object
bike1.setOwnerName("Adam Smith");
bike2 = new Bicycle( ); // Another object
bike2.setOwnerName("Ben Jones");
owner1 = bike1.getOwnerName( );
owner2 = bike2.getOwnerName( );
System.out.println(owner1 + " owns a bicycle.");
System.out.println(owner2 + " also owns one.");
} 21
}
THE PROGRAM STRUCTURE AND SOURCE FILES

BicycleRegistration Bicycle

There are two source


files. Each class
definition is stored in a
BicycleRegistration.java Bicycle.java separate file.

To run the program: 1. javac Bicycle.java (compile)


2. javac BicycleRegistration.java (compile)
3. java BicycleRegistration (run)

What if we enter java Bicycle instead? 22


MULTIPLE CONSTRUCTOR - 1
Given the Circle class,
class Circle {
public int radius; // Data member
public Circle (int r) { // Constructor
radius = r;
}
}
What if we want to add color to each circle?

We have to include more attributes and more 23

constructors
MULTIPLE CONSTRUCTOR – 2
Given
class Dice {
public int faceValue;
public Dice() {faceValue = 1; }
} // end class Dice
What if we want to create colored dice?
// Add more attributes and more constructors:
class Dice {
public int faceValue;
public String colour; // new attribute added
public Dice() {faceValue = 1;} // 4 constructors
public Dice(int n) {faceValue = n;}
public Dice(String c) {colour = c;}
public Dice(int n, String c) {faceValue = n; colour = c;}
} 24
MULTIPLE CONSTRUCTOR DEFINITION
 Java allows for multiple constructor definition.
 Which of these constructors is used depends on
which signature is matched
class Dice {
class TestDice { public int faceValue;
public static void main(String[ ] args) { public String colour;
Dice d = new Dice(); public Dice() {faceValue = 1;}
Dice d1 = new Dice(6); public Dice(int n) {faceValue = n;}
Dice d2 = new Dice(″white″); public Dice(String c) {colour = c;}
} public Dice(int n, String c)
} {faceValue = n; colour = c;}
}

25
INSTANCE METHODS
Methods declared in a class are called instance methods
and they can be invoked through an object of the class.
e.g. The method to roll a Dice object:
public void roll() {
faceValue = (int) (Math.random() * 6)+1);
}

26
USING AN INSTANCE METHOD
class TestDice {
public static void main(String [] args) {
Dice d = new Dice();
System.out.println(″face of the Dice is ″ + d.faceValue);
d.roll();
System.out.println(″face of the Dice is ″ + d.faceValue);
} // end main
} // end class TestDice
class Dice {
public int faceValue;
public String colour;
public Dice() {faceValue = 1; }
public void roll() {
faceValue = (int) (Math.random() * 6)+1;
} 27
} // end class Dice
LOCAL VARIABLE, PARAMETER & DATA MEMBER
 An identifier appearing inside a method can be a
local variable, a parameter, or a data member.
 The rules are
 If there’s a matching local variable declaration or a
parameter, then the identifier refers to the local
variable or the parameter.
 Otherwise, if there’s a matching data member
declaration, then the identifier refers to the data
member.
 Otherwise, it is an error because there’s no matching
declaration.
 Note that a parameter is regarded as a local
variable and therefore it is invalid to have a local
variable to have the same name as a parameter 28
VARIABLE MATCHING

class MusicCD {

private String artist;


private String title;
private String id;

public MusicCD(String name1, String name2) {

String ident;

artist = name1;

title = name2;

ident = artist.substring(0,2) + "-" +

title.substring(0,9);

id = ident;
} 29
...
}
CLASS VARIABLES -1
 A class variable or static variable refers to a variable
declared with modifier static
 Each class variable has only one copy, belonged to the
class but shared by all objects of the same class.
class Dice {
public int faceValue;
public String colour;
public static int max = 6;
public Dice() { faceValue = 1; }
public Dice(String c) { colour = c; }
public Dice(int n) { faceValue = n; }
public void roll() {
faceValue= (int)(Math.random()*max)+1);
} // end roll method
30
} // end class
CLASS VARIABLES -2
There are two ways of accessing class variables with the
use of the access operator .:
 Through the class
 e.g. Dice.max
 Through an object
 e.g System.out.println(d1.max); // d1 is a Dice object

class TestDice {
public static void main(String [] args) {
Dice d1 = new Dice(″red″);
Dice d2 = new Dice(5);
// ….
System.out.println(″The max value for d1 is ″ + d1.max);
System.out.println(″The max value for d2 is ″ + Dice.max);
} // end main
31
} // end class TestDice
CLASS METHODS - 1
 We use the reserved word static to define a class method.
public static int gcd(int m, int n) {
//the code implementing the Euclidean algorithm
}

 All methods of Math class are class methods


 Calling a class method through a class directly:
 Math.sqrt(d); // d is a double
 Math.random(); // Return a random fraction
 Integer.parseInt(s); // s is a numeric string
 MyClass.gcd(m,n); // gcd() is a class method of MyClass
// and m and n are 2 integers
32
CLASS METHODS - 2
 Class methods can only change class variables, if there are any.
 When an object changes a class variable, the new value will be
used by all other objects of the same class as well.
class Dice {
public int faceValue;
public String colour;
public static int max = 6;
public Dice() { faceValue = 1; }
public Dice(String c) { colour = c; }
public Dice(int n) { faceValue = n; }
public void roll() {
faceValue= (int)(Math.random()*max)+1);
} // end method
public static void changeMax(int n) {
max = n;
} // end method
} // end class Dice 33
CLASS METHODS - 3
There are two ways of referencing class methods:
 Through the class
 e.g. Dice.changeMax(12)
 Through an object
 e.g d1.changeMax(12);

class TestDice {
public static void main(String [ ] args) {
Dice d1 = new Dice(″red″);
// ….
Dice.changeMax(5);
System.out.println(″The max value for d1 is ″ + Dice.max);
d1.changeMax(6);
System.out.println(″The max value is now ″+Dice.max); 34
}
}
PRINTING FLOATING POINT NUMBERS
class TestFormat {
public static void main(String [ ] args) {
double num = 123.45678901234567890;
double num1 = 1.2345678901234567890;
System.out.println("num is " + num); // Print 17 digits
System.out.println("num1 is " + num1);
// Last digit printed is not accurate
} // end main
} // end class

> java TestFormat


num is 123.45678901234568
num1 is 1.2345678901234567

35
THE DECIMALFORMAT CLASS
Use a DecimalFormat object to format the numerical
output.
double num = 123.45789345;

DecimalFormat df = new DecimalFormat(“0.000”);


//three decimal places

System.out.print(num);
123.45789345

System.out.print(df.format(num));
123.458
36
SCANNER METHODS
Use a Scanner object to input data:
Scanner input = new Scanner(System.in);
Method Example
nextByte( ) byte b = input.nextByte( );
nextDouble( ) double d = input.nextDouble( );
nextFloat( ) float f = input.nextFloat( );
nextInt( ) int i = input.nextInt( );
nextLong( ) long l = input.nextLong( );
nextShort( ) short s = input.nextShort( );
next() String str = input.next();
nextLine() String str = input.nextLine();
37
THE MATH CLASS
 The Math class contains class methods for commonly
used mathematical functions.

double num, x, y;

x = …;
y = …;

num = Math.sqrt(Math.max(x, y) + 12.4);

38
SOME MATH CLASS METHODS
Method Description
exp(a) Natural number e raised to the power of a.

log(a) Natural logarithm (base e) of a.

floor(a) The largest whole number less than or


equal to a.
The larger of a and b.
max(a,b)
pow(a,b) The number a raised to the power of b.

sqrt(a) The square root of a.

sin(a) The sine of a. (Note: all trigonometric


functions are computed in radians)

Which method should we use if we want to find log base 10?


39
RANDOM NUMBER GENERATION - 1
 The Math.random method returns a number (double)
X, where 0.0 <= X < 1.0
 To return a random integer in [min, max] inclusively,
where min <= max, use the formula

X × (max − min +1) + min

int randomNumber =
(int) (Math.floor(Math.random()
* (max – min + 1)) + min);
RANDOM NUMBER GENERATION - 2
 We can also use the nextInt(n) method of the Random
class to generate a random number between 0 and n-1,
inclusive.
import java.util.Random;
Random random = new Random();
int number = random.nextInt(11);
//return x, 0 <= x <= 10

To return a random integer in [min, max] inclusively:

int number = random.nextInt( max – min + 1) + min;


RANDOM NUMBER GENERATION - 3
import java.util.*;
class SelectWinner {
public static void main( String[ ] args ) {
int startingNumber; //the starting number
int count; //the number of party goers
int winningNumber; //the winner
int min, max; //the range of numbers to generate
Scanner scan = new Scanner(System.in);
System.out.print("Enter the starting number M: ");
startingNumber = scan.nextInt();
System.out.print("Enter the number of party goers:");
count = scan.nextInt();
min = startingNumber;
max = startingNumber + count -1;
winningNumber = (int) (Math.floor(Math.random() * count ) + min);
System.out.println("\nThe Winning Number is " + winningNumber); 42
}
}
THE GREGORIANCALENDAR CLASS

 Use a GregorianCalendar object to manipulate


calendar information
GregorianCalendar today, independenceDay;

today = new GregorianCalendar();

independenceDay
= new GregorianCalendar(1965, 7, 9);
//month 7 means August; 0 means January

To use GregorianCalendar , have to


import java.util.*;
43
RETRIEVING CALENDAR INFORMATION
The class constants for retrieving different pieces of
calendar information from a Calendar object
(which is part of a GregorianCalendar object ).

44
SAMPLE CALENDAR RETRIEVAL

GregorianCalendar cal = new GregorianCalendar();


//Assume today is Dec 18, 2008

System.out.print(“Today is ” +
(cal.get(Calendar.MONTH)+1) + “/” +
cal.get(Calendar.DATE) + “/” +
cal.get(Calendar.YEAR));

Output
Today is 12/18/2008

45
USEFUL METHODS ON CALENDAR
computeTime()
Converts calendar field values to the time value (millisecond
offset from the Epoch (January 1, 1970 00:00:00.000 GMT )).
isLeapYear(int year)
Determines if the given year is a leap year.
add(int field, int amount)
Adds or subtracts the specified amount of time to the given
calendar field, based on the calendar's rules.
after(Object when)
Returns whether this Calendar represents a time after the time
represented by the specified Object.
before(Object when)
Returns whether this Calendar represents a time before the
time represented by the specified Object.
compareTo(Calendar anotherCalendar)
Compares the time values (millisecond offsets from the Epoch)
represented by two Calendar objects.
get(int field)
Returns the value of the given calendar field. 46

S-ar putea să vă placă și