1 / 24

CSC 1051 – Data Structures and Algorithms I

CSC 1051 – Data Structures and Algorithms I. Designing Classes II m ethods and encapsulation . Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu /~map/1051/. Getting to know classes so far.

montana
Télécharger la présentation

CSC 1051 – Data Structures and Algorithms I

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CSC 1051 – Data Structures and Algorithms I Designing Classes II methods and encapsulation Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ CSC 1051 M.A. Papalaskari, Villanova University

  2. Getting to know classes so far • Predefined classes from the Java API. • Defining classes of our own … • Our classes: • Account • Die • Shoe • Person • Driver classes: • Transactions, OnePercent • RollingDice • YouVeGotShoes (Project 7) • PeopleBeingPeople (Lab 8) Next: Focus on method definition/invocation CSC 1051 M.A. Papalaskari, Villanova University

  3. //********************************************************************//******************************************************************** // RollingDice.java Author: Lewis/Loftus // Demonstrates the creation and use of a user-defined class. //******************************************************************** public class RollingDice { //----------------------------------------------------------------- // Creates two Die objects and rolls them several times. //----------------------------------------------------------------- public static void main (String[] args) { Die die1, die2; intsum; die1 = new Die(); die2 = new Die(); die1.roll(); die2.roll(); System.out.println ("Die One: " + die1 + ", Die Two: " + die2); die1.roll(); die2.setFaceValue(4); System.out.println ("Die One: " + die1 + ", Die Two: " + die2); sum = die1.getFaceValue() + die2.getFaceValue(); System.out.println ("Sum: " + sum); sum = die1.roll() + die2.roll(); System.out.println ("Die One: " + die1 + ", Die Two: " + die2); System.out.println ("New sum: " + sum); } } Sample Run Die One: 5, Die Two: 2 Die One: 1, Die Two: 4 Sum: 5 Die One: 4, Die Two: 2 New sum: 6 CSC 1051 M.A. Papalaskari, Villanova University

  4. //********************************************************************//******************************************************************** // Die.java Author: Lewis/Loftus // // Represents one die (singular of dice) with faces showing values // between 1 and 6. //******************************************************************** public class Die { private final intMAX = 6; // maximum face value private intfaceValue; // current value showing on the die //----------------------------------------------------------------- // Constructor: Sets the initial face value. //----------------------------------------------------------------- public Die() { faceValue = 1; } //----------------------------------------------------------------- // Rolls the die and returns the result. //----------------------------------------------------------------- public introll() { faceValue = (int)(Math.random() * MAX) + 1; return faceValue; } continue CSC 1051 M.A. Papalaskari, Villanova University

  5. continue //----------------------------------------------------------------- // Face value mutator. //----------------------------------------------------------------- public void setFaceValue (intvalue) { faceValue = value; } //----------------------------------------------------------------- // Face value accessor. //----------------------------------------------------------------- public intgetFaceValue() { return faceValue; } //----------------------------------------------------------------- // Returns a string representation of this die. //----------------------------------------------------------------- public String toString() { String result = Integer.toString(faceValue); return result; } } CSC 1051 M.A. Papalaskari, Villanova University

  6. RollingDice Die faceValue : int main (args: String[]) : void roll() : int setFaceValue(value : int) : void getFaceValue() : int toString() : String UML Class Diagrams UML = Unified Modelling Language • Example: A UML class diagram for the RollingDice program:

  7. UML class diagram for Transactions program?

  8. char calc (intnum1, intnum2, String message) { intsum = num1 + num2; char result = message.charAt (sum); return result; } Method definition • parameters • return type • return statement charch= obj.calc (start, 2, "ABCDE"); CSC 1051 M.A. Papalaskari, Villanova University

  9. compute myMethod myMethod(); Method Control Flow • If the called method is in the same class, only the method name is needed CSC 1051 M.A. Papalaskari, Villanova University

  10. main doIt helpMe obj.doIt(); helpMe(); Method Control Flow • The called method is often part of another class or object CSC 1051 M.A. Papalaskari, Villanova University

  11. Invoking methods within the same class • An object’s method may access any of its other methods directly. Eg: public addInterest(double rate) { deposit (rate*balance); } • Thus the dot operator is an addressing mechanism. Note that it can also be used to access an object’s or class’s data directly, for example • acct1.name • Color.black • more on this later (encapsulation) CSC 1051 M.A. Papalaskari, Villanova University

  12. Invoking methods within the same class public static void main (String[] args) { printManyGreetings(5); } • The main method can do this too! • assumes printManyGreetings()is defined in the same class •  A convenient way to test methods CSC 1051 M.A. Papalaskari, Villanova University

  13. Invoking methods within the same class public static void main (String[] args) { printManyGreetings(5); } • The main method can do this too! • assumes printManyGreetings()is defined in the same class • NOTE: Since main() is static, printManyGreetings()must also be static CSC 1051 M.A. Papalaskari, Villanova University

  14. Implementing printManyGreetings() method: Invoking the method: printManyGreetings(5); CSC 1051 M.A. Papalaskari, Villanova University

  15. More Method Examples: • Write a method with two doubleparamentersa and b that computes and returns the sum of squares of its two parameters (i.e., a2 + b2). • How do we invoke the method to compute & print: (14.8)2 + (37.65)2? CSC 1051 M.A. Papalaskari, Villanova University

  16. More Method Examples: • Write a method with oneintparameter num, that returns a String composed of “Happy Birthday” numtimes • How do we invoke the method to print “happy birthday” 4 times? CSC 1051 M.A. Papalaskari, Villanova University

  17. Methods Client Data Encapsulation • An encapsulated object can be thought of as a black box -- its inner workings are hidden from the client • The client invokes the interface methods and they manage the instance data Violating Encapsulation It is possible for a class to access the instance data of another class directly CSC 1051 M.A. Papalaskari, Villanova University

  18. deposit() withdraw() addInterest() name acctNumber balance Violating Encapsulation - WRONG • It is possible for a class to access the instance data of another class directly – but it’s not a good idea! • See Account.java • See ImInUrClassMessingUrInstanceData.java Account.java ImInUrClassMessingUrInstanceData.java acct1.name = “Joe”; CSC 1051 M.A. Papalaskari, Villanova University

  19. deposit() withdraw() addInterest() Transactions.java name acctNumber balance Use Accessors & Mutators - RIGHT • Indirect access through methods • accessors and mutators (“getters” and “setters”) • Usually named getX() and setX() Account.java Methods Example int x1 = acct1.getBalance(); Data CSC 1051 M.A. Papalaskari, Villanova University

  20. Visibility Modifiers • In Java, we enforce encapsulation through the appropriate use of visibility modifiers: • public – can be referenced from other classes • private – can be referenced only within that class: • protected – involves inheritance (discussed later) • Data declared without a visibility modifier have default visibility and can be referenced by any class in the same package • An overview of all Java modifiers is presented in Appendix E CSC 1051 M.A. Papalaskari, Villanova University

  21. Violating Encapsulation experiment • Revisit your solution for the Account Class Exercise • Add some code to the OnePercent.java class to modify the value of an instance variable, eg: • This should work as expected • Now modify Account.java – insert the modifier private in front of that variable declaration: • Re-compile the Account class and run your program again. Note the error you get. acct1.name = “Joe”; private String name; CSC 1051 M.A. Papalaskari, Villanova University

  22. public constants are ok Example: The Account class can have a constant for the interest rate: A driver class (eg, OnePercent.java) can access this constant directly: public final double RATE = 0.015; System.out.print ("Interest rate = " + acct1.RATE); CSC 1051 M.A. Papalaskari, Villanova University

  23. public constants are ok Example: The Account class can have a constant for the interest rate: A driver class (eg, OnePercent.java) can access this constant directly without creating an object: Usually, constants are declared static public final static double RATE = 0.015; System.out.print ("Interest rate = " + acct1.RATE); System.out.print ("Interest rate = " + Account.RATE); CSC 1051 M.A. Papalaskari, Villanova University

  24. public private Variables Methods Visibility Modifiers – the RULES NO (but OK for public constants) Yes Yes, for support methods only Yes CSC 1051 M.A. Papalaskari, Villanova University

More Related