02 - objects and classes - a developers perspective - how do i create my own classes? how do i...
TRANSCRIPT
02 - Objects and Classes02 - Objects and Classes- A Developer’s - A Developer’s Perspective -Perspective -
How do I create my own How do I create my own classes? classes?
How do I design “good” How do I design “good” classes?classes?
© S. Uchitel, 2004 2
Classes in JavaClasses in Java//declares package to which class belongs to.//declares package to which class belongs to.package uk.ac.ic.doc.su2.examples; package uk.ac.ic.doc.su2.examples;
import uk.ac.ic.doc.su2.utils.Position; import uk.ac.ic.doc.su2.utils.Position; //Import declarations//Import declarations
public class Car { public class Car {
// // fields declarationsfields declarationsint mileage; int mileage;
Position current; Position current; // Note that this is a reference // Note that this is a reference variable...variable...
// Constructors// Constructors Car() {...}Car() {...}Car(Position p) {...}Car(Position p) {...}
// Methods // Methods void move(Position p) {…}void move(Position p) {…}
}}
Car
mileage:intcurrent:Position
Car(p: Position)Car()
move(p:Position):void
© S. Uchitel, 2004 3
ConstructorsConstructors
......
// Constructors// Constructors Car () { Car () { // no parameters required// no parameters required
// Places car in default position.// Places car in default position.mileage = 0;mileage = 0;current = new Position();current = new Position();
} }
Car(Position pos) {Car(Position pos) {// User defines initial position of car.// User defines initial position of car.mileage = 0;mileage = 0;current = pos.clone();current = pos.clone();
} } }}
Constructors do not have return types, why?
Car
mileage:intcurrent:Position
Car(p: Position)Car()
move(p:Position):void
© S. Uchitel, 2004 4
Methods Methods
// moves the car in a direction// moves the car in a directionvoid move(Position p) { void move(Position p) {
int distance = current.calculateDistance(p) ;int distance = current.calculateDistance(p) ;mileage = mileage + distance;mileage = mileage + distance;
}}
implementation (or body)
declaration (signature)return type (may be void i.e. nothing)method name formal parameters
Car
mileage:intcurrent:Position
Car(p: Position)Car()
move(p:Position):void
© S. Uchitel, 2004 5
Alternative to initialising field Alternative to initialising field valuesvalues
Fields that are Fields that are primitive typesprimitive types may be given initial may be given initial values when declared...values when declared...
......public class Car { public class Car {
int mileage = 0; int mileage = 0; Position current; Position current; // Adding “= new Position()” here is // Adding “= new Position()” here is NOT allowedNOT allowed
Car () { Car () { current = new Position();current = new Position();
} }
Car(Position pos) {Car(Position pos) {current = pos.clone();current = pos.clone();
} } ......
© S. Uchitel, 2004 6
Writing your own classes...Writing your own classes...
Five issues to think about:Five issues to think about: Which Which packagepackage the class will belong to. the class will belong to. What What constructorsconstructors are to be provided and are to be provided and
what should they do.what should they do. What What methodsmethods are to be provided and what are to be provided and what
should they do.should they do. What What fieldsfields will store state of objects. will store state of objects. Are there any tricky Are there any tricky implementation detailsimplementation details..
Then, just write the class!Then, just write the class!
© S. Uchitel, 2004 7
Creating Class DiceCreating Class Dice methods: methods:
roll() roll() rolls the dice, rolls the dice, getTop() getTop() returns the number on the top side of the dice returns the number on the top side of the dice
(integer between 1 and 6)(integer between 1 and 6) getBottom()getBottom() returns the number on the bottom side of the returns the number on the bottom side of the
dice (integer between 1 and 6)dice (integer between 1 and 6) implementation details: implementation details:
Use Use java.util.Randomjava.util.Random to simulate throwing the dice. to simulate throwing the dice. Use rule: “Use rule: “The opposite sides of a dice add to 7The opposite sides of a dice add to 7””
fields: fields: ““int top;” int top;” to store top side of the dice.to store top side of the dice. ““java.util.Random generator;” java.util.Random generator;” to simulate rolling the dice.to simulate rolling the dice.
package: package: doc.ic.ac.uk.su2.gamesdoc.ic.ac.uk.su2.games
constructor:constructor: dice() dice() creates a dice. No default initial top value.creates a dice. No default initial top value.
Dice
top: intgenerator: Random
getTop():voidgetBottom():voidroll():void
© S. Uchitel, 2004 8
Skeleton for Class DiceSkeleton for Class Dice// Package declaration goes here...// Package declaration goes here...
/* /* Import declarations go here...Import declarations go here...
*/*/
class Dice {class Dice { /*/*
Field declarations go here...Field declarations go here...*/*/
/*/*Constructors go hereConstructors go here
*/*/
/*/*Methods go here...Methods go here...
*/*/}}
Dice.javaDice.java
package uk.ac.ic.doc.su2.games;package uk.ac.ic.doc.su2.games;import java.util.Random;import java.util.Random;
class Dice { class Dice { int top; // Number on top side of diceint top; // Number on top side of dice Random generator; //For “rolling dice”Random generator; //For “rolling dice”
Dice() { //Sets up dice and rolls it once.Dice() { //Sets up dice and rolls it once.generator = new Random();generator = new Random();top = generator.nextInt(6)+1;top = generator.nextInt(6)+1;
}}
void roll() { //Rolls dice by random choice from 1-6void roll() { //Rolls dice by random choice from 1-6top = generator.nextInt(6)+1; top = generator.nextInt(6)+1;
}}
int getTop() { //Returns number on top side of diceint getTop() { //Returns number on top side of dicereturn top;return top;
}}
int getBottom() { //Returns number on bottom of diceint getBottom() { //Returns number on bottom of dicereturn 7-top;return 7-top;
}}}}
Dice
top: intgenerator: Random
getTop():voidgetBottom():voidroll():void
Dice.javaDice.java
package uk.ac.ic.doc.su2.games;package uk.ac.ic.doc.su2.games;import java.util.Random;import java.util.Random;
class Dice { class Dice { int top; // Number on top side of diceint top; // Number on top side of dice Random generator; //For “rolling dice”Random generator; //For “rolling dice”
Dice() { //Sets up dice and rolls it once.Dice() { //Sets up dice and rolls it once.generator = new Random();generator = new Random();roll();roll();
}}
void roll() { //Rolls dice by random choice from 1-6void roll() { //Rolls dice by random choice from 1-6top = generator.nextInt(6)+1; top = generator.nextInt(6)+1;
}}
int getTop() { //Returns number on top side of diceint getTop() { //Returns number on top side of dicereturn top;return top;
}}
int getBottom() { //Returns number on bottom of diceint getBottom() { //Returns number on bottom of dicereturn 7-getTop();return 7-getTop();
}}}}
Dice
top: intgenerator: Random
getTop():voidgetBottom():voidroll():void
Improved!
Using our very own class DiceUsing our very own class Dicepublic class Craps {public class Craps {//Throws two dice. Users wins if they guess the sum. //Throws two dice. Users wins if they guess the sum. //Requires and integer as parameter//Requires and integer as parameter
public static void main(String [] args) {public static void main(String [] args) { int guess = convertStringToInt(args[0]);int guess = convertStringToInt(args[0]); Dice d1 = new Dice(); Dice d2 = new Dice();Dice d1 = new Dice(); Dice d2 = new Dice();
System.out.println("Rolling...");System.out.println("Rolling..."); d1.roll(); d2.roll();d1.roll(); d2.roll();
System.out.println("Its "+d1.getTop()+" and "+d2.getTop());System.out.println("Its "+d1.getTop()+" and "+d2.getTop());
if (d1.getTop() + d2.getTop() != guess)if (d1.getTop() + d2.getTop() != guess)System.out.println("Tough luck!");System.out.println("Tough luck!");
elseelseSystem.out.println("You win");System.out.println("You win");
}}
static int convertStringToInt (String s) {...}static int convertStringToInt (String s) {...} }}}}
Dice
top: intgenerator: Random
getTop():voidgetBottom():voidroll():void
A Problem with DiceA Problem with Dice......
public class CheatCraps {public class CheatCraps {
public static void main(String [] args) {public static void main(String [] args) { int guess = convertStringToInt(args[0]);int guess = convertStringToInt(args[0]); Dice d1 = new Dice(); Dice d2 = new Dice();Dice d1 = new Dice(); Dice d2 = new Dice();
System.out.println("Rolling...");System.out.println("Rolling..."); d1.roll(); d2.roll();d1.roll(); d2.roll(); d2.top = guess - d1.getTop();d2.top = guess - d1.getTop();
System.out.println("Its "+d1.getTop()+" and "+d2.getTop());System.out.println("Its "+d1.getTop()+" and "+d2.getTop());
if (d1.getTop() + d2.getTop() != guess)if (d1.getTop() + d2.getTop() != guess) System.out.println("Tough luck!");System.out.println("Tough luck!");
elseelseSystem.out.println("You win");System.out.println("You win");
}}
......
Dice
top: intgenerator: Random
getTop():voidgetBottom():voidroll():void
© S. Uchitel, 2004 13
EncapsulationEncapsulation
An object should hide its implementation details.An object should hide its implementation details. Why?Why?
To prevent the user from misusing the object.To prevent the user from misusing the object. e.g. No cheating!e.g. No cheating!
To protect the user from misusing the objectTo protect the user from misusing the object e.g. A car with negative mileage?e.g. A car with negative mileage?
To make the user’s life simplerTo make the user’s life simpler Less details, allows easier comprehension.Less details, allows easier comprehension. What is this Random class? Does the user need to What is this Random class? Does the user need to
know?know? Insulate user from changes in the implementationInsulate user from changes in the implementation
Store bottom side of dice instead of top side. Store bottom side of dice instead of top side.
© S. Uchitel, 2004 14
Encapsulation: Using StringsEncapsulation: Using Strings
Users don’t need to know the answers to: Users don’t need to know the answers to: Are Strings stored in an array of char?Are Strings stored in an array of char? Does compareTo compare sizes before Does compareTo compare sizes before
comparing content? comparing content? Users do need to know:Users do need to know:
Is there a maximum length for StringsIs there a maximum length for Strings What values returned by compareTo mean What values returned by compareTo mean
that the strings are equal?that the strings are equal?
+ String(str: String)+ charAt(index: int): char+ compareTo(str: String): int
String
© S. Uchitel, 2004 15
Encapsulation: Using InputReaderEncapsulation: Using InputReader
How does readInt() work?How does readInt() work? Does it store digits individually? Or an array of Does it store digits individually? Or an array of
char? or a String? char? or a String? How does it detect keys pressed? How does it detect keys pressed? Will it round of if “2.4” is entered? Will it round of if “2.4” is entered? If the input is not an integer, will the program If the input is not an integer, will the program
crash?crash?
+ readInt(): int+ readString(): String
InputReader
© S. Uchitel, 2004 16
Summary: EncapsulationSummary: Encapsulation
Objects should present their users with an Objects should present their users with an interface that interface that gives them access specific behavioursgives them access specific behaviours hides internal data representationhides internal data representation hides algorithmic detailshides algorithmic details preserves data integrity preserves data integrity
It is It is your job your job as a developer to design as a developer to design classes that ensure the above!classes that ensure the above!
© S. Uchitel, 2004 17
VisibilityVisibility
Visibility is about who can access methods Visibility is about who can access methods and fields.and fields.
It is a mechanism for implementing It is a mechanism for implementing encapsulation.encapsulation.
Methods and fields can be declared to be Methods and fields can be declared to be PublicPublic: Anyone can access: Anyone can access PackagePackage (the default): Anyone from within the (the default): Anyone from within the
packagepackage PrivatePrivate: Accessible from within the class: Accessible from within the class ProtectedProtected: Related to inheritance (will see later...): Related to inheritance (will see later...)
For now, we will focus on public and private.For now, we will focus on public and private.
© S. Uchitel, 2004 18
Public/Private in Practice Public/Private in Practice
Make private as many members as possibleMake private as many members as possible Provide access to a method only when needed. Provide access to a method only when needed.
Methods invoked only from within the class Methods invoked only from within the class should always be private. should always be private.
Instance variables are usually private Instance variables are usually private
publicpublic privateprivate
FieldsFields Violates Violates encapsulationencapsulation
Enforce Enforce
EncapsulationEncapsulation
MethodsMethods Provide service Provide service to class usersto class users
Support other Support other methods in the methods in the
classclass
© S. Uchitel, 2004 19
Visibility: Revisiting the Dice ClassVisibility: Revisiting the Dice Class
Encapsulation ensured by:Encapsulation ensured by: Making top and generator fields privateMaking top and generator fields private Providing getBottom() to “hide bottom = 7-top” Providing getBottom() to “hide bottom = 7-top”
rule.rule.
+ Dice()+ getTop(): int+ getBottom(): int
- top: int- generator: Random
Dice
“-” means private
“+” means public
© S. Uchitel, 2004 20
Properly encapsulated Class DiceProperly encapsulated Class Dice......publicpublic class Dice { class Dice { private private int top; // Number on top side of diceint top; // Number on top side of dice privateprivate Random generator; //For random number generation Random generator; //For random number generation
publicpublic Dice() { //Sets up dice by rolling it initially. Dice() { //Sets up dice by rolling it initially.generator = new Random();generator = new Random();roll();roll();
}}
publicpublic void roll() { //Rolls dice-random choice from 1-6 void roll() { //Rolls dice-random choice from 1-6top = generator.nextInt(6)+1; top = generator.nextInt(6)+1;
}}
publicpublic int getTop() { //Returns number on die’s top side int getTop() { //Returns number on die’s top sidereturn top;return top;
}}
publicpublic int getBottom() {//Returns number on die’s bottom int getBottom() {//Returns number on die’s bottomreturn 7-getTop();return 7-getTop();
}}}}
© S. Uchitel, 2004 21
No more problems with DiceNo more problems with Dice
package uk.ac.ic.doc.su2.examples;package uk.ac.ic.doc.su2.examples;import uk.ac.ic.doc.su2.games.*;import uk.ac.ic.doc.su2.games.*;
public class Cheat {public class Cheat {//Throws two dice and celebrate when sum is 7//Throws two dice and celebrate when sum is 7public static void main(String [] args) {public static void main(String [] args) { Dice d1 = new Dice();Dice d1 = new Dice(); Dice d2 = new Dice();Dice d2 = new Dice(); //d1.top = -1; // Compiler will not compile//d1.top = -1; // Compiler will not compile //d2.top = 8; // with these lines.//d2.top = 8; // with these lines. if (d1.getTop() + d2.getTop() != 7)if (d1.getTop() + d2.getTop() != 7)
System.out.println(“Tough luck!”);System.out.println(“Tough luck!”); else else
System.out.println(“You win”);System.out.println(“You win”);}}
}}
Dice
-top: int-generator: Random
+getTop():void+getBottom():void+roll():void
+getTop():void+getBottom():void+roll():void
Dice
© S. Uchitel, 2004 22
Private Methods: ExamplePrivate Methods: Example
......public class Lecturer {public class Lecturer { private String name;private String name; private String login;private String login; ........
publicpublic void setLogin(String newLogin) { void setLogin(String newLogin) { if checkLogin(newLogin)if checkLogin(newLogin)
login = newLogin;login = newLogin;}}privateprivate boolean checkLogin(String newLogin) { boolean checkLogin(String newLogin) {
if newLogin.contains(‘@’);if newLogin.contains(‘@’);return false;return false;
}}}}
Lecturer-name: int-login: Random
+getLogin():String+setLogin(String):void-checkLogin():booleanPrivate methods serve as auxiliary, Private methods serve as auxiliary,
internal methods to the class.internal methods to the class.
Can constructors Can constructors
be declared private?be declared private?
© S. Uchitel, 2004 23
Class VisibilityClass Visibility
Classes are normally declared Classes are normally declared publicpublic::
public class Lecturerpublic class Lecturer
Ensures accessibility from outside the package Ensures accessibility from outside the package they were defined in.they were defined in.
Only one public class per fileOnly one public class per file There is no point in declaring a class as There is no point in declaring a class as
privateprivate. . Why?Why? Classes with Classes with packagepackage visibility: auxiliary to visibility: auxiliary to
the package…the package…
© S. Uchitel, 2004 24
Package VisibilityPackage Visibility
May be accessed only from within the package.May be accessed only from within the package. It is the default (no visibility modifiers used)It is the default (no visibility modifiers used) Should be used with extreme care!Should be used with extreme care! ClassesClasses
For classes that are auxiliary to the packageFor classes that are auxiliary to the package e.g. e.g. class Supervisor_Student_Pairclass Supervisor_Student_Pair
Methods and FieldsMethods and Fields Allows classes within the package to access internals.Allows classes within the package to access internals. Possibly for efficiency or code reuse.Possibly for efficiency or code reuse. Violates encapsulation but limits the damage.Violates encapsulation but limits the damage.
(Classes in same package are supposed to know better)(Classes in same package are supposed to know better) e.g. e.g. Engine myEngine;Engine myEngine; e.g. e.g. boolean checkLogin();boolean checkLogin();
© S. Uchitel, 2004 25
Visibility: SummaryVisibility: Summary
publicpublic packagepackage
(default)(default)privateprivate
within within classclass
YesYes YesYes YesYes
within within packagepackage
YesYes YesYes NoNo
AnywhereAnywhere YesYes NoNo NoNo
© S. Uchitel, 2004 26
Class Scope... (1/2)Class Scope... (1/2)
Up to nowUp to now Fields and methods had Fields and methods had object scope.object scope. A method is on a specific object, requesting A method is on a specific object, requesting
the object to do something, and/or changing the object to do something, and/or changing the object’s state and/or retrieving information the object’s state and/or retrieving information on its state.on its state.
Fields are part of the state of the object.Fields are part of the state of the object. You cannot access these fields and methods if You cannot access these fields and methods if
there is no objectthere is no object
© S. Uchitel, 2004 27
Class Scope... (2/2)Class Scope... (2/2)
We now introduce We now introduce class scopeclass scope fields and fields and methodsmethods They are associated with a class and not a They are associated with a class and not a
specific object.specific object. They are declared as They are declared as staticstatic They are accessed through their class (not They are accessed through their class (not
through an object). through an object). e.g. e.g. ClassName.method(); ClassName.method(); e.g. e.g. ClassName.fieldClassName.field
Only one Only one static fieldstatic field is created per class (as is created per class (as opposed to one per object for normal fields)opposed to one per object for normal fields)
© S. Uchitel, 2004 28
Static Fields: Usage (1)Static Fields: Usage (1)
System.out is a reference to a PrintStream object that outputs System.out is a reference to a PrintStream object that outputs to the standard Java outputto the standard Java output
System.out is a System.out is a global objectglobal object
package java.lang;package java.lang;public class System {public class System { public static PrintStream out = new PrintStream(....);public static PrintStream out = new PrintStream(....);
////The "standard" output stream. The "standard" output stream. public static PrintStream err = new PrintStream(...);public static PrintStream err = new PrintStream(...);
////The "standard" error output stream. The "standard" error output stream. public static InputStream in = new InputStream(...); public static InputStream in = new InputStream(...);
////The "standard" input stream. The "standard" input stream. ..............}}
System
out : PrintStreamerr : PrintStreamin : InputStream
public class Example{public class Example{..............
System.out.println(“Hello World!”);System.out.println(“Hello World!”);..............}}
© S. Uchitel, 2004 29
Static Fields: Usage (2)Static Fields: Usage (2)
Fields declared as Fields declared as finalfinal are constants (their value are constants (their value cannot changecannot change
Math
E : double = 2.718281828PI : double = 3.141592654
sin(:double):doublecos(:double):doubletan(:double):double
public class Math{public class Math{ public final static double E = 2.718281828;public final static double E = 2.718281828; public final static double PI = 3.141592654;public final static double PI = 3.141592654;..............}} PI is global constant
accessed Math.PI
How can we change the aboveto make PI a constant only to the class?
and a constant to the package?
© S. Uchitel, 2004 30
Static Methods: Usage (1)Static Methods: Usage (1)
kenya.io.InputReader.readInt() is a kenya.io.InputReader.readInt() is a global methodglobal method.. Note how it uses indirectly the global object System.in.Note how it uses indirectly the global object System.in. Note that isr and tokenizer have package visibility.Note that isr and tokenizer have package visibility.
public class InputReaderpublic class InputReader{{ static InputStreamReader isr = new InputStreamReader(System.in);static InputStreamReader isr = new InputStreamReader(System.in); static StreamTokenizer tokenizer = new StreamTokenizer(isr);static StreamTokenizer tokenizer = new StreamTokenizer(isr); ...... public static int readInt() {public static int readInt() {
......tokenizer.nextToken(); //reads indirectly through System.intokenizer.nextToken(); //reads indirectly through System.in......
}}}}
kenya.io.InputReader
~ isr: InputStreamReader; ~ tokenizer: StreamTokenizer;
+ readInt()
© S. Uchitel, 2004 31
Static Methods: Usage (2)Static Methods: Usage (2)
main()main() is always declared static. It is a is always declared static. It is a global global methodmethod. . The starting of a program is not associated to any object. The starting of a program is not associated to any object. It is at a (public) class level.It is at a (public) class level.
public class Hello {public class Hello {public static void main(String [] args) {public static void main(String [] args) { System.out.println("Type in your name.");System.out.println("Type in your name."); String name = InputReader.readString();String name = InputReader.readString(); System.out.println("Hello + name + "!");System.out.println("Hello + name + "!");}}
}} Note usage of static field of Note usage of static field of outout and static method and static method
readString()readString()
© S. Uchitel, 2004 32
Class Scope: SummaryClass Scope: Summary
Use sparingly.Use sparingly. Only if Only if
you want to have only one piece of storage for you want to have only one piece of storage for a particular piece of data, regardless of how a particular piece of data, regardless of how many objects are created, or even if no objects many objects are created, or even if no objects are created. are created.
you need a method that isn’t associated with you need a method that isn’t associated with any particular object of this class. any particular object of this class.
© S. Uchitel, 2004 33
Putting it all together (3)Putting it all together (3)package uk.ac.ic.doc.su2.examples;package uk.ac.ic.doc.su2.examples;import java.util.Random; import java.util.Random; import kenya.io.InputReader;import kenya.io.InputReader;
public class Guess {public class Guess {//Implements the “guess-what-number-I’m-thinking of” game//Implements the “guess-what-number-I’m-thinking of” gamepublic static void main(String [] args) {public static void main(String [] args) { Random generator = new Random();Random generator = new Random(); int number = generator.nextInt(10)+1; int number = generator.nextInt(10)+1;
//Pick a number randomly between 1 and 10//Pick a number randomly between 1 and 10 System.out.println(“Take a guess (1 to 10)”); System.out.println(“Take a guess (1 to 10)”); if (number == InputReader.readInt())if (number == InputReader.readInt())
System.out.println(“You win”);System.out.println(“You win”); else else
System.out.println(“Tough Luck”);System.out.println(“Tough Luck”);}}
}}
Warning! This is a copy of a previous slide
© S. Uchitel, 2004 34
Putting it all together (3)Putting it all together (3)package uk.ac.ic.doc.su2.examples;package uk.ac.ic.doc.su2.examples;import java.util.Random; import java.util.Random; import kenya.io.InputReader;import kenya.io.InputReader;
public class Guess {public class Guess {//Implements the “guess-what-number-I’m-thinking of” game//Implements the “guess-what-number-I’m-thinking of” gamepublic static void main(String [] args) {public static void main(String [] args) { Random generator = new Random();Random generator = new Random(); int number = generator.nextInt(10)+1; int number = generator.nextInt(10)+1;
//Pick a number randomly between 1 and 10//Pick a number randomly between 1 and 10 System.out.println(“Take a guess (1 to 10)”); System.out.println(“Take a guess (1 to 10)”); if (number == InputReader.readInt())if (number == InputReader.readInt())
System.out.println(“You win”);System.out.println(“You win”); else else
System.out.println(“Tough Luck”);System.out.println(“Tough Luck”);}}
}}
out is a static field of class System
readInt is a static method of class InputReader
main is declared as static in class Guess
Warning! This is a copy of a previous slide
© S. Uchitel, 2004 35
Putting it all together (3)Putting it all together (3)package uk.ac.ic.doc.su2.examples;package uk.ac.ic.doc.su2.examples;import java.util.Random; import java.util.Random; import kenya.io.InputReader;import kenya.io.InputReader;
public class Guess {public class Guess {//Implements the “guess-what-number-I’m-thinking of” game//Implements the “guess-what-number-I’m-thinking of” gamepublic static void main(String [] args) {public static void main(String [] args) { Random generator = new Random();Random generator = new Random(); int number = generator.nextInt(10)+1; int number = generator.nextInt(10)+1;
//Pick a number randomly between 1 and 10//Pick a number randomly between 1 and 10 System.out.println(“Take a guess (1 to 10)”); System.out.println(“Take a guess (1 to 10)”); if (number == InputReader.readInt())if (number == InputReader.readInt())
System.out.println(“You win”);System.out.println(“You win”); else else
System.out.println(“Tough Luck”); System.out.println(“Tough Luck”); }}
}}
println is NOT a static static method!It is being called on an
object referenced by out.
Warning! This is a copy of a previous slide
© S. Uchitel, 2004 36
The Pseudo-SingletonThe Pseudo-Singleton
class King { class King { // only one globally available instance// only one globally available instance
// Attributes// Attributesstatic King _king;static King _king;
// Constructo// Constructor r King () { } King () { }
static King lookupKing () {static King lookupKing () {if (_king == null) { if (_king == null) { // the king is dead// the king is dead
_king = new King(); _king = new King(); }}return _king; return _king; // long live the King// long live the King
}}}}
Can you notice any problems with this?
© S. Uchitel, 2004 37
SingletonSingleton
"There can be only one"
public class King { public class King { // only one globally available instance// only one globally available instance
// Attributes// Attributesprivate static King _king;private static King _king;
// Constructo// Constructor r private King () { } private King () { }
public static King lookupKing () {public static King lookupKing () {if (_king == null) { if (_king == null) { // the king is dead// the king is dead
_king = new King(); _king = new King(); }}return _king; return _king; // long live the King// long live the King
}}}}
© S. Uchitel, 2004 38
Overloading Overloading
Overloading: methods with the same name within a class. Overloading: methods with the same name within a class. Example 1: Constructor overloading (as seen previously)Example 1: Constructor overloading (as seen previously)
Car(); Car(String Colour); Car(String Colour, String Model);Car(); Car(String Colour); Car(String Colour, String Model); Example 2: Method overloading. E.g. Example 2: Method overloading. E.g.
class Multiplier {class Multiplier {static int mult(int, int); static int mult(int, int); // (1)// (1)static float mult(float, float); static float mult(float, float); // (2)// (2)
} }
Condition for overloadingCondition for overloading: Method parameters distinguish : Method parameters distinguish each overloaded method definitioneach overloaded method definition
Java can distinguish the types of the parameters when a Java can distinguish the types of the parameters when a call is made and choose the appropriate method. e.g., call is made and choose the appropriate method. e.g.,
float c=1.2; float f=2.3;float c=1.2; float f=2.3;long d = Multiplier.mult(c, f);long d = Multiplier.mult(c, f);
© S. Uchitel, 2004 39
Overloading (2)Overloading (2)
Java can performs implicit type conversionsJava can performs implicit type conversions int x=2; float y=1.5; float d = Multiplier.multi(x,y); int x=2; float y=1.5; float d = Multiplier.multi(x,y);
//Calls multi(float, float). Java converts automatically int to float//Calls multi(float, float). Java converts automatically int to float
Java will always chose the Java will always chose the "most specific""most specific" call (i.e., call (i.e., minimum number of conversions) if one exists. minimum number of conversions) if one exists. Otherwise it returns an error. Otherwise it returns an error.
Note that the return type does not distinguish Note that the return type does not distinguish overloaded methods: -> overloaded methods: -> Name clashName clash
class Multiplier {class Multiplier { static int mult(float, float); static int mult(float, float); // (1)// (1)
static float mult(float, float); static float mult(float, float); // ERROR! multiple // ERROR! multiple definitiondefinition
// of mult(float, float)// of mult(float, float) }}
Please correct your notes…
© S. Uchitel, 2004 40
CallbacksCallbacks
call
call me back
Thank you for holding! All our customer advisorsare busy at the moment…
This is Ken. How can I help?
I want a refund!!
© S. Uchitel, 2004 41
What is What is thisthis??
An object’s An object’s self-referenceself-reference. . Self-reference cannot be known at design Self-reference cannot be known at design
time.time. thisthis is an implicit reference to the object is an implicit reference to the object
currently executing a method. currently executing a method. It is a reference in the same way “Student s” It is a reference in the same way “Student s”
declares s as a reference to a student object.declares s as a reference to a student object. It is implicit because it doesn’t need to be It is implicit because it doesn’t need to be
explicitly declaredexplicitly declared
© S. Uchitel, 2004 42
this: usagethis: usage
public class Pair{ public class Pair{
private float x, y; private float x, y;
Pair(float x, float y) {Pair(float x, float y) {
this.x = x;this.x = x;
this.y = y;this.y = y;
}}
public String toString() {public String toString() {
return “(“ + this.x + “,” + this.y + “)”;return “(“ + this.x + “,” + this.y + “)”;
}}
} }
Here, “this” is needed. Here, “this” is needed. Distinguishes the object field Distinguishes the object field from the parameter of the methodfrom the parameter of the method
Here, use of “this” is unnecesary! Here, use of “this” is unnecesary!
© S. Uchitel, 2004 43
Where the compiler disagrees?Where the compiler disagrees?
class A {class A { private int i;private int i;
A(int j) { i= j;}A(int j) { i= j;}
void f() { void f() { this.i=3*this.i; this.i=3*this.i; // this =new A(4); // this =new A(4); // ERROR // ERROR cannot assign a value to cannot assign a value to
thisthis}}
void g() { this.f(); };void g() { this.f(); };
public static void main(String[] args) { public static void main(String[] args) { //this.i = 0; //this.i = 0; // // ERROR ERROR non-static variable cannot be non-static variable cannot be
// referenced from a static context. // referenced from a static context. Why?Why?}}
} }
© S. Uchitel, 2004 44
ChecklistChecklist
Defining Classes, Fields and MethodsDefining Classes, Fields and Methods ConstructorsConstructors the the PackagePackage keyword keyword EncapsulationEncapsulation Visibility: Public, Private, PackageVisibility: Public, Private, Package Class, Field and Method VisibilityClass, Field and Method Visibility Class scope, the Class scope, the staticstatic keyword keyword Static methods and fieldsStatic methods and fields Singleton patternSingleton pattern The The this this keywordkeyword