introduction to objects and object-oriented...
TRANSCRIPT
Instructor: Azhar
Introduction to Objects and
Object-Oriented Programming Week 4
2
Agendas
Language FeaturesJava DataTypes
Objects and Classes Access ControlClass Methods and Variables
3
Java Data TypesPrimitive Data TypesReference Types
4
Primitive Data TypesThe usual suspects:
byte, short, int, longcharbooleanfloat, double
The usual operators and rules apply mostly
5
6
Reference Types (1)Can't write about objects without referring to themReference value: the only way to refer to an objectJava has:
reference values (or just references)reference expressionsreference variablesassignment of references
7
Declarations, Variables, Assignments
C-like rules apply for the most part
Type specifier followed by identifier list
8
Number typesint: integers, no fractional part1, -4, 0
double: floating-point numbers (double precision)0.5, -3.11111, 4.3E24, 1E-14
9
Syntax: Constant DefinitionExample: Purpose: In a method:
final typeName variableName= expression ;In a class:
accessSpecifier static final typeName variableName = expression;
Example:final double NICKEL_VALUE =0.05; public static final double LITERS_PER_GALLON =3.785;
Purpose:To define a constant of a particular type
10
Division and Remainder
/ is the division operator If both arguments are integers, the result is an integer. The remainder is discarded 7.0 / 4 = 1.757 / 4 = 1 Get the remainder with % (pronounced "modulo")7 % 4 = 3
11
Mathematical Functions
closest integer to xMath.round(x)
sine, cosine, tangent (x in radian)
Math.sin(x), Math.cos(x), Math.tan(x)
natural logMath.log(x)
exMath.exp(x)
power xyMath.pow(x, y)
square rootMath.sqrt(x)
12
Syntax: Static Method CallClassName. methodName( Tparameters)
Example:Math.sqrt(4)
Purpose:To invoke a static method (a method that
doesn'toperate on an object) and supply its
parameters.
13
Type ConversionIn assignment, types must match.double total = "a lot"; // no Use “cast” (int) to convert floating-point values to integer values:int pennies = (int)(total * 100);Cast discards fractional part.
Use Math.round for rounding:int dollar = (int)Math.round(total);
14
Syntax: Cast
(typeName)expression
Example: (int)(x + 0.5)
(int)Math.round(100 * f)
Purpose:To convert an expression to a different type
15
Objects
Only accessed via reference values
Rectangle r1= new Rectangle( );
Not seen— we (the programmers) only
get references to them and send them
messages.
r1.getArea();
16
Objects Can NOT Beassigned to a variable
int x=Rectangle new Rectangle();the value of an expression
new Rectangle()= x+y; passed as an argument in a message to an object
r1.setArea( new Rectangle());returned by an object responding to a messageDeclared
Rectangle r1; // Does not create the object.
17
But References Can Be
assigned to a variablethe value of an expressionpassed as an argument in a message to an objectreturned by an object responding to a messagedeclared
18
Different Reference Types
References to objects of different classes are different types
Every class implicitly defines a distinct reference type
19
References Are Not Pointers
can't take "address" of object— can not refer to object without referencecan’t do arithmetic with referencesJava has no pointers
20
What's The Use Of References?
only way to access an objectonly way to send a message to an object
21
Messages: SendingMessage Form:
methodName(argument1, argument2, …, argumentN)
Sending a Message (Form):
reference . message
22
Messages: Response From Receiver
value
send message form can be used in expression
often the right side of an assignment statement
can be primitive data OR a reference to an
object
void
23
Java Pre-defined Classes
Huge number of predefined classesutlity, I/O, GUI, network, time/day, database, math, etc.
PrintStream class:println(string), print(string)
String class:toUpperCase, trim, substring, indexOf, etc.
File classdelete, renameTo
24
Java Pre-defined Objects
System.out, System.err, System.inString constants
25
Sample Code 1String s;
int i=0, k;
s = "hello, world";
k = s.length();
while (i<k-1) {
System.out.println(s.substring(0,i+1));
i++;
}
26
Cascading Messages
String s;
s = "Hello".concat(" World").toUpperCase();
System.out.println(s);
27
Creating Objects
new keywordconstructor + argumentsexpression's value is reference to create object
28
Creating And Using An Object: Example
File junk;junk = new File("garbage");junk.delete();
29
Class Definitions
class NameOfClass {
method definitions (including constructors)
instance variable declarations
}
30
Method Definitions
similar to function definitionsadditional keywords: public or privateoptional keyword: staticoptional phrase: throws SomeKindOfException
31
Class Definition Example 1 class Laugher4 {
public Laugher4(String defaultSyl) {default = defaultSyl;
}
public void laugh() {System.out.println(default);
}
private String default;}
32
Class Definition Example 2 class Laugher2 {
public Laugher2() { default = "ha"; }
public Laugher2(String defaultSyl) {default = defaultSyl;
}
public void laugh() {System.out.println(default);
}
public void laugh(String syl) {System.out.println(syl);
}private String default;
}
33
Signatures and Overloading
Signature: method name + argument typesOverloading: methods of the same name but different signaturespublic Laugher2() { public Laugher2(String defaultSyl) {public void laugh() {public void laugh(String syl) {
34
A Name Classclass Name {
private String first, last, title;
public Name(String first, String last) {this.first = first;this.last = last;
}public String getInitials() {
String s; // M Azhars = first.substring(0,1); // Ms = s.concat("."); //M. s = s.concat(last.substring(0,1));//M.As = s.concat(".");//M.Areturn s;
}
35
Name Class (2) public String getLastFirst() {
return lastName.concat(", ").concat(firstName);}
public String getFirstLast() {return first.concat(" ").concat(last);
}
public void setTitle(String newTitle) {title = newTitle;
}
36
Name Class (3)public static Name read(BufferedReader br)
throws Exception {String first, last;first = br.readLine();last = br.readLine();return new Name(first,last);
}
}
37
Using The Name Classpublic class TestName{ public static void main(String [] args){BufferedReader br = new BufferedReader( new InputStreamReader(
System.in)); Name n; n = Name.read(br); System.out.println(n.getInitials());}
}
38
Class Variables: StaticAlthough a class is not an object, a class can have both class variables and class methods.Class variables and class methods can exist whether or not any object is created. Class variables and class methods are indicated with the keyword static.
39
Static (Class) MethodsA class/static method, as we have already seen, is a method
that: • exists as a member of a class, • may be invoked using either the class name or the
name of an object, • may not access instance variables, (Since class
methods may be invoked regardless of whether or not any object have been created, object/instance variables cannot be accessed by static methods.)
• is often used when it is important to know how many class instances exist or to restrict the number of instances of a class.
40
Static (Class) VariablesIf a class contains a static variable then:
• All objects/instances of the class share that variable.• There is only one version of the variable defined for the whole class.• The variable belongs to the class.• The variable exists regardless of whether or not any objects have been created.• The variable may be accessed using either the class name or an object name, if an object has been created.
Example:Static or class variables are often used for constants. The Math class contains two class constants: Math.PI and Math.E ( approximate value: 2.71828).
41
Static
The Java System library contains many class/static methods. The methods of Math are all static as are the (final) variables. Of course, allowing static methods and variables is contrary to the principles of object-oriented programming since Java is providing a mechanism for what amounts to global variables and methods!
42
Static
The following simple class contains two class/static variables:
• The variable count keeps track of the number of Circle objects that have been created. One version of count exists for the entire class. All objects access this same variable.
• The static variable pi is a constant. Notice the keyword final. Also note that pi is declared public so that any other class may access it as Circle.pi.
43
Example
44
Test Driver
45
Explanation
The class method, getCount(), returns the number of Circle objects that have been created.Notice that getCount() accesses count – a class/static variable. Remember: a static method cannot access an instance variable, since instance variables may not even exist.The example also illustrates use of the keyword this. Sometimes the parameter has the same name as one of the instance variables. To differentiate between the parameter and the private variable, use the keyword this. As in C++, this is a reference to the invoking object.
46
Scope and Lifetimesobjectslocal (method) variables and parametersinstance variablesclass variables
47
Objects and ClassesObject: entity that you can manipulate in your programs (by invoking methods) Each object belongs to a class Class: Set of objects with the same behavior Class determines legal methods"Hello".println() // Error"Hello".length() // OK
48
Syntax: Object Constructionnew ClassName(parameters)
Example:new Rectangle(5, 10, 20, 30)new Car("BMW 540ti", 2004)
Purpose:To construct a new object, initialize it with the construction parameters, and return a reference to the constructed object.
49
Object VariablesDeclare and optionally initialize:Rectangle cerealBox = new Rectangle(5, 10, 20, 30);Rectangle crispyCrunchy; Apply methods:cerealBox.translate(15, 25);Share objects:r = cerealBox;
50
Uninitialized and Initialized Variables
Uninitialized
Initialized
51
Two Object Variables Referring to the Same Object
52
Syntax: Variable DefinitionTypeName variableName;
TypeName variableName = expression;
Example:Rectangle cerealBox; String name ="Dave";
Purpose:To define a new variable of a particular type
and optionally supply an initial value
53
Writing a Test ProgramInvent a new class, say MoveTest Supply a main method Place instructions inside the main method Import library classes by specifying the package and class name:import java.awt.Rectangle; You don't need to import classes in the java.lang package such as String and System
54
Syntax: Importing a Class from a Package
importpackageName.ClassName ;
Example:import java.awt.Rectangle;
Purpose:To import a class from a package for use in a program
55
File MoveRect.java1 import java.awt.Rectangle; 2 3 public class MoveTest 4 { 5 public static void main(String[] args) 6 { 7 Rectangle cerealBox = new Rectangle(5,
10, 20, 30); 8 // move the rectangle 9 cerealBox.translate(15, 25);10 // print the moved rectangle11 System.out.println(cerealBox); 12 }
56
A Simple Classpublic class Greeter { public String sayHello() { String message ="Hello,World!";
return message; } }
57
Method Definitionaccess specifier (such as public) return type (such as String or void) method name (such as sayHello) list of parameters (empty for sayHello) method body in { }
58
Syntax: Method Implementationpublic class ClassName { ... accessSpecifier returnType methodName(parameterType parameterName,...) { method body } ... } …Continue
59
…ContinueExample:
public class Greeter { public String sayHello() { String message ="Hello,World!"; return message; } }
Purpose:
To define the behavior of a method A method definition specifies the method name, parameters, and the statements for carrying out the method's actions
60
Syntax: The return Statement return expression;or return;
Example:return message;
Purpose:To specify the value that a method returns, and
exit the method immediately. The return value
becomes the value of the method call
expression.
61
Testing a ClassTest class: a class with a main method that contains statements to test another class.
Typically carries out the following steps: Construct one or more objects of the class that is being tested. Invoke one or more methods. Print out one or more results
62
A Test Class for the Greeter Class
public class GreeterTest {
public static void main(String [] args)) { Greeter worldGreeter = new Greeter();
System.out.println(worldGreeter.sayHello());
}}
63
Building a Test Program1. Make a new subfolder for your
program. 2. Make two files, one for each class.
3. Compile both files. 4. Run the test program.
64
Testing with the SDK Toolsmkdir greeter cd greeter edit Greeter.java edit GreeterTest.java javac Greeter.java javac GreeterTest.java java GreeterTest
65
Instance Fieldspublic class Greeter{
...private String name;
}access specifier (such as private) type of variable (such as String) name of variable (such as name)
66
Instance Fields
67
Accessing Instance Fields
The sayHello method of the Greeter class can access the private instance field:public String sayHello(){String message = "Hello, " + name + "!";return message;}
68
Other methods cannot:public class GreeterTest{public static void main(String[] args){. . .System.out.println(daveGreeter.name); // ERROR}} Encapsulation = Hiding data and providing access through methods
69
Syntax: Instance Field Declaration
accessSpecifier class ClassName{ ... accessSpecifier fieldType fieldName; ... }
70
Example:public class Greeter
{ ... private String name; ... }
Purpose:To define a field that is present in every object of a class
71
Constructors• A constructor initializes the instance variables • Constructor name = class namepublic class Greeter(){ public Greeter(String aName) { name = aName; } . . .}Invoked in new expressionnew Greeter("Dave")
72
Syntax: Constructor Implementation
accessSpecifier class ClassName { ... accessSpecifier ClassName(parameterTypeparameterName ...) { constructor implementation } ... }
73
Example:public class Greeter { ... public Greeter(String aName) { name = aName; } ...}
Purpose:
To define the behavior of a constructor, which is used to initialize the instance fields of newly created objects
74
File Greeter.java1 public class Greeter 2 { 3 public Greeter(String aName) 4 { 5 name = aName; 6 } 7 8 public String sayHello() 9 { 10 String message = "Hello, " + name + "!"; 11 return message; 12 } 13 private String name; 14 }
75
File GreeterTest.java1 public class GreeterTest 2 { 3 public static void main(String[] args) 4 { 5 Greeter worldGreeter = new Greeter("World"); 6 System.out.println(worldGreeter.sayHello()); 7 8 Greeter daveGreeter = new Greeter("Dave"); 9 System.out.println(daveGreeter.sayHello()); 10 } 11 }
76
Designing the Public InterfaceBehavior of bank account:
• deposit money • withdraw money • get balance
Methods of BankAccount class:deposit withdraw getBalance
77
BankAccount Public Interfacepublic BankAccount() public BankAccount(double initialBalance) public void deposit(double amount) public void withdraw(double amount) public double getBalance()
78
Using the Public Interface• Transfer balance
double amt = 500;momsSavings.withdraw(amt);harrysChecking.deposit(amt);
Add interestdouble rate = 5; // 5%double amt = acct.getBalance()* rate / 100;acct.deposit(amt);
79
Commenting the Public Interface
/** Withdraws money from the bank account. @param the amount to withdraw */ public void withdraw(double amount) { implementation filled in later }
80
/** Gets the current balance of the bank account. @return the current balance */ public double getBalance() { implementation filled in later }
81
Class Comment /**
A bank account has a balance that can be changed by deposits and withdrawals. */ public class BankAccount { ...}
82
Javadoc Method Summary
83
Javadoc Method Detail
84
BankAccount Class Implementation
Determine instance variables to hold object stateprivate double balance
Implement methods and constructors
85
File BankAccount.java
1 /** 2 A bank account has a balance that can be
changed by 3 deposits and withdrawals. 4 */ 5 public class BankAccount 6 {
86
7 /** 8 Constructs a bank account with a zero
balance 9 */ 10 public BankAccount() 11 { 12 balance = 0; 13 } 14
87
15 /**
16 Constructs a bank account with a given balance
17 @param initialBalance the initial balance
18 */
19 public BankAccount(double initialBalance)
20 {
21 balance = initialBalance;
22 }
88
23 24 /** 25 Deposits money into the bank account. 26 @param amount the amount to deposit 27 */ 28 public void deposit(double amount) 29 { 30 double newBalance = balance + amount; 31 balance = newBalance; 32 } 33
89
34 /**
35 Withdraws money from the bank account.
36 @param amount the amount to withdraw
37 */
38 public void withdraw(double amount)
39 {
40 double newBalance = balance - amount;
41 balance = newBalance;
42 }
43
90
44 /** 45 Gets the current balance of the bank account. 46 @return the current balance 47 */ 48 public double getBalance() 49 { 50 return balance; 51 } 52 53 private double balance; 54 }
91
File BankAccountTest.java1 /** 2 A class to test the BankAccount class. 3 */ 4 public class BankAccountTest5 { 6 /** 7 Tests the methods of the BankAccount class. 8 @param args not used 9 */
92
10 public static void main(String[] args) 11 { 12 BankAccount harrysChecking = new
BankAccount(); 13 harrysChecking.deposit(2000)14 harrysChecking.withdraw(500)15
System.out.println(harrysChecking.getBalance());
16 } 17 }
93
Variable TypesInstance fields (balance in BankAccount) Local variables (newBalance in deposit method) Parameter variables (amount in deposit method)
94
Explicit and Implicit Parameters
public void withdraw(double amount){ double newBalance = balance - amount; balance = newBalance;}
balance is the balance of the object to the left of the dot:
momsSavings.withdraw(500)means double newBalance = momsSavings.balance - amount;
momsSavings.balance = newBalance;