Presentation is loading. Please wait.

Presentation is loading. Please wait.

02 - Objects and Classes - A Developers Perspective - How do I create my own classes? How do I create my own classes? How do I design good classes? How.

Similar presentations


Presentation on theme: "02 - Objects and Classes - A Developers Perspective - How do I create my own classes? How do I create my own classes? How do I design good classes? How."— Presentation transcript:

1 02 - Objects and Classes - A Developers Perspective - How do I create my own classes? How do I create my own classes? How do I design good classes? How do I design good classes?

2 2 © S. Uchitel, 2004 Classes in Java //declares package to which class belongs to. package uk.ac.ic.doc.su2.examples; import uk.ac.ic.doc.su2.utils.Position; //Import declarations public class Car { // fields declarations int mileage; Position current; // Note that this is a reference variable... Position current; // Note that this is a reference variable... // Constructors Car() {...} Car(Position p) {...} // Methods void move(Position p) {…} } Car mileage:int current:Position Car(p: Position) Car() move(p:Position):void

3 3 © S. Uchitel, 2004 Constructors... // Constructors Car () { // no parameters required // Places car in default position. mileage = 0; current = new Position(); } Car(Position pos) { // User defines initial position of car. mileage = 0; current = pos.clone(); }} Constructors do not have return types, why? Car mileage:int current:Position Car(p: Position) Car() move(p:Position):void

4 4 © S. Uchitel, 2004 Methods // moves the car in a direction void move(Position p) { int distance = current.calculateDistance(p) ; mileage = mileage + distance; } implementation (or body) declaration (signature) return type (may be void i.e. nothing) method name formal parameters Car mileage:int current:Position Car(p: Position) Car() move(p:Position):void

5 5 © S. Uchitel, 2004 Alternative to initialising field values Fields that are primitive types may be given initial values when declared public class Car { int mileage = 0; Position current; // Adding = new Position() here is NOT allowed Position current; // Adding = new Position() here is NOT allowed Car () { current = new Position(); } Car(Position pos) { current = pos.clone(); }...

6 6 © S. Uchitel, 2004 Writing your own classes... Five issues to think about: Five issues to think about: Which package the class will belong to. Which package the class will belong to. What constructors are to be provided and what should they do. What constructors are to be provided and what should they do. What methods are to be provided and what should they do. What methods are to be provided and what should they do. What fields will store state of objects. What fields will store state of objects. Are there any tricky implementation details. Are there any tricky implementation details. Then, just write the class! Then, just write the class!

7 7 © S. Uchitel, 2004 Creating Class Dice methods: methods: roll() rolls the dice, roll() rolls the dice, getTop() returns the number on the top side of the dice (integer between 1 and 6) getTop() returns the number on the top side of the dice (integer between 1 and 6) getBottom() returns the number on the bottom side of the dice (integer between 1 and 6) getBottom() returns the number on the bottom side of the dice (integer between 1 and 6) implementation details: implementation details: Use java.util.Random to simulate throwing the dice. Use java.util.Random to simulate throwing the dice. Use rule: The opposite sides of a dice add to 7 Use rule: The opposite sides of a dice add to 7 fields: fields: int top; to store top side of the dice. int top; to store top side of the dice. java.util.Random generator; to simulate rolling the dice. java.util.Random generator; to simulate rolling the dice. package: package: doc.ic.ac.uk.su2.games doc.ic.ac.uk.su2.games constructor: constructor: dice() creates a dice. No default initial top value. dice() creates a dice. No default initial top value. Dice top: int generator: Random getTop ():void getBottom():void roll():void

8 8 © S. Uchitel, 2004 Skeleton for Class Dice // Package declaration goes here... /* Import declarations go here... */ class Dice { /* Field declarations go here... *//* Constructors go here *//* Methods go here... */}

9 Dice.java package uk.ac.ic.doc.su2.games; import java.util.Random; class Dice { int top; // Number on top side of dice int 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(); top = generator.nextInt(6)+1; } void roll() { //Rolls dice by random choice from 1-6 void roll() { //Rolls dice by random choice from 1-6 top = generator.nextInt(6)+1; } int getTop() { //Returns number on top side of dice int getTop() { //Returns number on top side of dice return top; } int getBottom() { //Returns number on bottom of dice int getBottom() { //Returns number on bottom of dice return 7-top; }} Dice top: int generator: Random getTop ():void getBottom():void roll():void

10 Dice.java package uk.ac.ic.doc.su2.games; import java.util.Random; class Dice { int top; // Number on top side of dice int 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(); roll(); } void roll() { //Rolls dice by random choice from 1-6 void roll() { //Rolls dice by random choice from 1-6 top = generator.nextInt(6)+1; } int getTop() { //Returns number on top side of dice int getTop() { //Returns number on top side of dice return top; } int getBottom() { //Returns number on bottom of dice int getBottom() { //Returns number on bottom of dice return 7-getTop(); }} Dice top: int generator: Random getTop ():void getBottom():void roll():void Improved!

11 Using our very own class Dice public class Craps { //Throws two dice. Users wins if they guess the sum. //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!"); else else System.out.println("You win"); } static int convertStringToInt (String s) {...} static int convertStringToInt (String s) {...} }} Dice top: int generator: Random getTop ():void getBottom():void roll():void

12 A Problem with Dice... 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!"); else else System.out.println("You win"); }... Dice top: int generator: Random getTop ():void getBottom():void roll():void

13 13 © S. Uchitel, 2004 Encapsulation 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 object To protect the user from misusing the object e.g. A car with negative mileage? e.g. A car with negative mileage? To make the users life simpler To make the users life simpler Less details, allows easier comprehension. Less details, allows easier comprehension. What is this Random class? Does the user need to know? What is this Random class? Does the user need to know? Insulate user from changes in the implementation Insulate user from changes in the implementation Store bottom side of dice instead of top side. Store bottom side of dice instead of top side.

14 14 © S. Uchitel, 2004 Encapsulation: Using Strings Users dont need to know the answers to: Users dont 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 comparing content? Does compareTo compare sizes before comparing content? Users do need to know: Users do need to know: Is there a maximum length for Strings Is there a maximum length for Strings What values returned by compareTo mean that the strings are equal? What values returned by compareTo mean that the strings are equal? + String(str: String) + charAt(index: int): char + compareTo(str: String): int String

15 15 © S. Uchitel, 2004 Encapsulation: Using InputReader How does readInt() work? How does readInt() work? Does it store digits individually? Or an array of char? or a String? Does it store digits individually? Or an array of 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 crash? If the input is not an integer, will the program crash? + readInt(): int + readString(): String InputReader

16 16 © S. Uchitel, 2004 Summary: Encapsulation Objects should present their users with an interface that Objects should present their users with an interface that gives them access specific behaviours gives them access specific behaviours hides internal data representation hides internal data representation hides algorithmic details hides algorithmic details preserves data integrity preserves data integrity It is your job as a developer to design classes that ensure the above! It is your job as a developer to design classes that ensure the above!

17 17 © S. Uchitel, 2004 Visibility Visibility is about who can access methods and fields. Visibility is about who can access methods and fields. It is a mechanism for implementing encapsulation. It is a mechanism for implementing encapsulation. Methods and fields can be declared to be Methods and fields can be declared to be Public: Anyone can access Public: Anyone can access Package (the default): Anyone from within the package Package (the default): Anyone from within the package Private: Accessible from within the class Private: Accessible from within the class Protected: Related to inheritance (will see later...) Protected: Related to inheritance (will see later...) For now, we will focus on public and private. For now, we will focus on public and private.

18 18 © S. Uchitel, 2004 Public/Private in Practice Make private as many members as possible Make private as many members as possible Provide access to a method only when needed. Methods invoked only from within the class should always be private. Provide access to a method only when needed. Methods invoked only from within the class should always be private. Instance variables are usually private Instance variables are usually private publicprivate Fields Violates encapsulation EnforceEncapsulation Methods Provide service to class users Support other methods in the class

19 19 © S. Uchitel, 2004 Visibility: Revisiting the Dice Class Encapsulation ensured by: Encapsulation ensured by: Making top and generator fields private Making top and generator fields private Providing getBottom() to hide bottom = 7-top rule. Providing getBottom() to hide bottom = 7-top rule. + Dice() + getTop(): int + getBottom(): int - top: int - generator: Random Dice - means private+ means public

20 20 © S. Uchitel, 2004 Properly encapsulated Class Dice... public class Dice { private int top; // Number on top side of dice private int top; // Number on top side of dice private Random generator; //For random number generation private Random generator; //For random number generation public Dice() { //Sets up dice by rolling it initially. public Dice() { //Sets up dice by rolling it initially. generator = new Random(); roll(); } public void roll() { //Rolls dice-random choice from 1-6 public void roll() { //Rolls dice-random choice from 1-6 top = generator.nextInt(6)+1; } public int getTop() { //Returns number on dies top side public int getTop() { //Returns number on dies top side return top; } public int getBottom() {//Returns number on dies bottom public int getBottom() {//Returns number on dies bottom return 7-getTop(); }}

21 21 © S. Uchitel, 2004 No more problems with Dice package uk.ac.ic.doc.su2.examples; import uk.ac.ic.doc.su2.games.*; public class Cheat { //Throws two dice and celebrate when sum is 7 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); }} Dice -top: int -generator: Random +getTop ():void +getBottom():void +roll():void +getTop ():void +getBottom():void +roll():void Dice

22 22 © S. Uchitel, 2004 Private Methods: Example... public class Lecturer { private String name; private String name; private String login; private String login; public void setLogin(String newLogin) { if checkLogin(newLogin) if checkLogin(newLogin) login = newLogin; login = newLogin;} private boolean checkLogin(String newLogin) { if if return false; }} Lecturer -name: int -login: Random +getLogin():String +setLogin(String):void -checkLogin():boolean Private methods serve as auxiliary, internal methods to the class. Can constructors be declared private?

23 23 © S. Uchitel, 2004 Class Visibility Classes are normally declared public: Classes are normally declared public: public class Lecturer Ensures accessibility from outside the package they were defined in. Ensures accessibility from outside the package they were defined in. Only one public class per file Only one public class per file There is no point in declaring a class as private. Why? There is no point in declaring a class as private. Why? Classes with package visibility: auxiliary to the package… Classes with package visibility: auxiliary to the package…

24 24 © S. Uchitel, 2004 Package 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! Classes Classes For classes that are auxiliary to the package For classes that are auxiliary to the package e.g. class Supervisor_Student_Pair e.g. class Supervisor_Student_Pair Methods and Fields Methods 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. (Classes in same package are supposed to know better) Violates encapsulation but limits the damage. (Classes in same package are supposed to know better) e.g. Engine myEngine; e.g. Engine myEngine; e.g. boolean checkLogin(); e.g. boolean checkLogin();

25 25 © S. Uchitel, 2004 Visibility: Summary publicpackage(default)private within class YesYesYes within package YesYesNo AnywhereYesNoNo

26 26 © S. Uchitel, 2004 Class Scope... (1/2) Up to now Up to now Fields and methods had object scope. Fields and methods had object scope. A method is on a specific object, requesting the object to do something, and/or changing the objects state and/or retrieving information on its state. A method is on a specific object, requesting the object to do something, and/or changing the objects state and/or retrieving information 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 there is no object You cannot access these fields and methods if there is no object

27 27 © S. Uchitel, 2004 Class Scope... (2/2) We now introduce class scope fields and methods We now introduce class scope fields and methods They are associated with a class and not a specific object. They are associated with a class and not a specific object. They are declared as static They are declared as static They are accessed through their class (not through an object). They are accessed through their class (not through an object). e.g. ClassName.method(); e.g. ClassName.method(); e.g. ClassName.field e.g. ClassName.field Only one static field is created per class (as opposed to one per object for normal fields) Only one static field is created per class (as opposed to one per object for normal fields)

28 28 © S. Uchitel, 2004 Static Fields: Usage (1) System.out is a reference to a PrintStream object that outputs to the standard Java output System.out is a reference to a PrintStream object that outputs to the standard Java output System.out is a global object System.out is a global object package java.lang; public class System { public static PrintStream out = new PrintStream(....); public static PrintStream out = new PrintStream(....); //The "standard" output stream. public static PrintStream err = new PrintStream(...); public static PrintStream err = new PrintStream(...); //The "standard" error output stream. public static InputStream in = new InputStream(...); public static InputStream in = new InputStream(...); //The "standard" input stream } System out : PrintStream err : PrintStream in : InputStream public class Example{ System.out.println(Hello World!); }

29 29 © S. Uchitel, 2004 Static Fields: Usage (2) Fields declared as final are constants (their value cannot change Fields declared as final are constants (their value cannot change Math E : double = PI : double = sin(:double):double cos(:double):double tan(:double):double public class Math{ public final static double E = ; public final static double E = ; public final static double PI = ; public final static double PI = ; } PI is global constant accessed Math.PI How can we change the above to make PI a constant only to the class? and a constant to the package?

30 30 © S. Uchitel, 2004 Static Methods: Usage (1) kenya.io.InputReader.readInt() is a global method. kenya.io.InputReader.readInt() is a global 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 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.in... }} kenya.io.InputReader ~ isr: InputStreamReader; ~ tokenizer: StreamTokenizer; + readInt()

31 31 © S. Uchitel, 2004 Static Methods: Usage (2) main() is always declared static. It is a global method. main() is always declared static. It is a global method. 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 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 out and static method readString() Note usage of static field of out and static method readString()

32 32 © S. Uchitel, 2004 Class Scope: Summary Use sparingly. Use sparingly. Only if Only if you want to have only one piece of storage for a particular piece of data, regardless of how many objects are created, or even if no objects are created. you want to have only one piece of storage for a particular piece of data, regardless of how many objects are created, or even if no objects are created. you need a method that isnt associated with any particular object of this class. you need a method that isnt associated with any particular object of this class.

33 33 © S. Uchitel, 2004 Putting it all together (3) package uk.ac.ic.doc.su2.examples; import java.util.Random; import kenya.io.InputReader; public class Guess { //Implements the guess-what-number-Im-thinking of game 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 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

34 34 © S. Uchitel, 2004 Putting it all together (3) package uk.ac.ic.doc.su2.examples; import java.util.Random; import kenya.io.InputReader; public class Guess { //Implements the guess-what-number-Im-thinking of game 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 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

35 35 © S. Uchitel, 2004 Putting it all together (3) package uk.ac.ic.doc.su2.examples; import java.util.Random; import kenya.io.InputReader; public class Guess { //Implements the guess-what-number-Im-thinking of game 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 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

36 36 © S. Uchitel, 2004 The Pseudo-Singleton class King { // only one globally available instance // Attributes static King _king; // Constructor King () { } static King lookupKing () { if (_king == null) { // the king is dead _king = new King(); } return _king; // long live the King }} Can you notice any problems with this?

37 37 © S. Uchitel, 2004 Singleton "There can be only one" public class King { // only one globally available instance // Attributes private static King _king; // Constructor private King () { } public static King lookupKing () { if (_king == null) { // the king is dead _king = new King(); } return _king; // long live the King }}

38 38 © S. Uchitel, 2004 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 { static int mult(int, int); // (1) class Multiplier { static int mult(int, int); // (1) static float mult(float, float); // (2) } Condition for overloading: Method parameters distinguish each overloaded method definition Condition for overloading: Method parameters distinguish each overloaded method definition Java can distinguish the types of the parameters when a call is made and choose the appropriate method. e.g., float c=1.2; float f=2.3; long d = Multiplier.mult(c, f); Java can distinguish the types of the parameters when a call is made and choose the appropriate method. e.g., float c=1.2; float f=2.3; long d = Multiplier.mult(c, f);

39 39 © S. Uchitel, 2004 Overloading (2) Java can performs implicit type conversions Java can performs implicit type conversions int x=2; float y=1.5; float d = Multiplier.multi(x,y); //Calls multi(float, float). Java converts automatically int to float int x=2; float y=1.5; float d = Multiplier.multi(x,y); //Calls multi(float, float). Java converts automatically int to float Java will always chose the "most specific" call (i.e., minimum number of conversions) if one exists. Otherwise it returns an error. Java will always chose the "most specific" call (i.e., minimum number of conversions) if one exists. Otherwise it returns an error. Note that the return type does not distinguish overloaded methods: -> Name clash Note that the return type does not distinguish overloaded methods: -> Name clash class Multiplier { static int mult(float, float); // (1) static float mult(float, float); // ERROR! multiple definition static float mult(float, float); // ERROR! multiple definition // of mult(float, float) } Please correct your notes…

40 40 © S. Uchitel, 2004 Callbacks call call me back Thank you for holding! All our customer advisors are busy at the moment… This is Ken. How can I help? I want a refund!!

41 41 © S. Uchitel, 2004 What is this ? An objects self-reference. An objects self-reference. Self-reference cannot be known at design time. Self-reference cannot be known at design time. this is an implicit reference to the object currently executing a method. this is an implicit reference to the object currently executing a method. It is a reference in the same way Student s declares s as a reference to a student object. It is a reference in the same way Student s declares s as a reference to a student object. It is implicit because it doesnt need to be explicitly declared It is implicit because it doesnt need to be explicitly declared

42 42 © S. Uchitel, 2004 this: usage public class Pair{ private float x, y; Pair(float x, float y) { this.x = x; this.y = y; } public String toString() { return ( + this.x +, + this.y + ); }} Here, this is needed. Distinguishes the object field from the parameter of the method Here, use of this is unnecesary!

43 43 © S. Uchitel, 2004 Where the compiler disagrees? class A { private int i; private int i; A(int j) { i= j;} void f() { this.i=3*this.i; // this =new A(4); // ERROR cannot assign a value to this } void g() { this.f(); }; public static void main(String[] args) { //this.i = 0; // ERROR non-static variable cannot be // referenced from a static context. Why? // referenced from a static context. Why?}}

44 44 © S. Uchitel, 2004 Checklist Defining Classes, Fields and Methods Defining Classes, Fields and Methods Constructors Constructors the Package keyword the Package keyword Encapsulation Encapsulation Visibility: Public, Private, Package Visibility: Public, Private, Package Class, Field and Method Visibility Class, Field and Method Visibility Class scope, the static keyword Class scope, the static keyword Static methods and fields Static methods and fields Singleton pattern Singleton pattern The this keyword The this keyword


Download ppt "02 - Objects and Classes - A Developers Perspective - How do I create my own classes? How do I create my own classes? How do I design good classes? How."

Similar presentations


Ads by Google