Presentation is loading. Please wait.

Presentation is loading. Please wait.

ENCAPSULATION. WHY ENCAPSULATE? So far, the objects we have designed have all of their methods and variables visible to any part of the program that has.

Similar presentations


Presentation on theme: "ENCAPSULATION. WHY ENCAPSULATE? So far, the objects we have designed have all of their methods and variables visible to any part of the program that has."— Presentation transcript:

1 ENCAPSULATION

2 WHY ENCAPSULATE? So far, the objects we have designed have all of their methods and variables visible to any part of the program that has a reference to the object. Thus, code other than a method of an object can change an object's instance variable. This is often unwise.

3 SCOPE/VISIBILITY MODIFIERS public: allows access from anywhere private: can only be accessed within its own class protected: can only be accessed within own class and subclasses internal: can be accessed by all classes in same package

4 THE PRIVATE VISIBILITY MODIFIER class CheckingAccount{ // data-declarations private var accountNumber:String; private var accountHolder:String; private var balance:Number; //constructors function CheckingAccount(accNumber:String, holder:String, start:Number ) { accountNumber = accNumber ; accountHolder = holder ; balance = start ; } // methods function currentBalance():Number { return balance ; } function processDeposit( amount:Number ) { balance = balance + amount ; } function processCheck( int amount ):void { var charge:Number; if ( balance < 100000 ) charge = 15; else charge = 0; balance = balance - amount - charge ; } Now only the methods of a CheckingAccount object can "see" the values in accountNumber, accountHolder, and balance.

5 ACCESS METHODS A class with private data, controls access to that data by using access methods. An access method is a method which uses the private data of its class and is visible to other classes. Some access methods alter data; others return a value but don't alter data.

6 EXAMPLE OF ACCESS METHODS class CheckingAccount{ private var accountNumber:String; private var accountHolder:String; private var balance:Number;.... } class CheckingAccountTester{ public main( ):void { var bobsAccount: CheckingAccount = new CheckingAccount( "999", "Bob", 100 ); Alert.show( bobsAccount.currentBalance() ); bobsAccount.processDeposit( 200 ); Alert.show( bobsAccount.currentBalance() ); }

7 CAREFUL ACCESS CONTROL It may seem a bit silly that the CheckingAccount class used private to prevent main() from seeing its variables, and then provided some methods so that main() could get at them anyway. But the idea of this is that the access methods could check each access to the private data. For example, a programmer can't increase the balance of a checking account by writing: bobsAccount.balance = bobsAccount.balance + 200; To increase the balance, the processDeposit() method must be used, which in a more elaborate program might check that the account is not frozen, might insist on a password before it changes anything, and might write a log file of every change.

8 ENCAPSULATION The programming technique we have been talking about is called encapsulation. Encapsulation means hiding the details of an object from the other parts of a program. The object can be used only through its access methods, which are carefully written to keep the object consistent and secure. Encapsulation makes an object look like a black box : The insides of the box are hidden from view. On the outside are some controls which are the only way that the user can use the box. The usual example of this is a TV set where most of the inner workings are sealed off from the user. The user interacts with the set using some well-defined controls. The controls are sometimes called the user interface. In object oriented programming, the programmer should try to make the interface to the object simple and useful. The inner workings of the object should be made private.

9 PRIVATE METHODS A private method is one that can be used only by the other methods of an object. Parts of a program outside of the object cannot directly invoke (use) a private method of the object.

10 THE PUBLIC VISIBILITY MODIFIER The private visibility modifier keeps outsiders from looking in. However, the access methods are intended for outsiders, and have to be visible to outsiders in order to be useful. The public access modifier explicitly says that a method or variable of an object can be accessed by code outside of the object. The public visibility modifier is usually used for all access methods and constructors in a class definition. Most instance variables are made private.

11 QUIZ ON CLASS DEFINITION Which of the following is the general scheme for a class definition: a. Class ClassName{ // Description of the instance variables. // Description of the constructors. // Description of the methods.} b. class ClassName{ // Description of the instance variables. // Description of the constructors. // Description of the methods.} c. ClassName{ // Description of the instance variables. // Description of the constructors. // Description of the methods.} d. class ClassName{ public static void main ( ) { // entire program goes here } }

12 Here is the general syntax for method definition: accessModifier methodName( parameterList ):returnType{ statements return returnValue;} What is true for the access Modifier ? a. It must always be private or public. b. It can be omitted, but if not omitted it must be private or public. c. It can be omitted, but if not omitted there are several choices, including private and public. d. The access modifier must agree with the type of the return value.

13 Here is the general syntax for method definition: accessModifier methodName( parameterList ):void{ statements return returnValue;} What is true for the returnType and the returnValue? a. The returnValue must be exactly the same type as the returnType. b. The returnValue must be the same type as the returnType, or be of a type that can be converted to returnType without loss of information. c. The returnValue can be any type, but will be automatically converted to returnType when the method returns to the caller. d. If the returnType is void then the returnValue can be any type.

14 What term is used for hiding the details of an object from the other parts of a program? a. Obfustication. b. Data Mining. c. Compilation. d. Encapsulation.

15 What is the effect of giving a class member private access? a. When a member of a class is declared private it can be used in only one place in a program. b. When a member of a class is declared private it can be used only in methods that are members of that class. c. When a member of a class is declared private it can only be used by other private members of other classes. d. When a member of a class is declared private there will be only one instance of it, no matter how many objects are instantiated.

16 Methods of a class that are used by "outsiders" to access private (and other) data of the class are called... a. Access methods. b. Private methods. c. Public methods. d. Member methods.

17 What will happen if a main() method of a "testing" class tries to access a private instance variable of an object using dot notation? a. The compiler will find the error and will not make a.class file. b. The compiler will automatically change the private variable to a public variable. c. The program will compile successfully, but the.class file will not run correctly. d. The program will compile and run successfully.

18 What access modifier explicitly says that a method or variable of an object can be accessed by code outside of the object? a. private b. public c. default d. static

19 Programming Exercises Exercise 1: Immutable Box Implement a class, Box. This implementation of Box will have encapsulation. Here is the documentation or specs for Box: class Box A class that implements a cardboard box. Constructors Box ( Number width, Number height, Number length ) Methods Number volume() Number area()

20 In the current implementation of Box make all the instance variables private. This means that only methods of a Box object can see that object's data. The object will be immutable if there are no access methods that make changes to this data. An immutable object is one whose data does not change. You may remember that String objects are immutable---once the characters of the String are set with a constructor they never change (although they can be used to create other String objects.) Give public access to the methods of Box. Test your Box class with several versions of this program: var box:Box = new Box( 2.5, 5.0, 6.0 ); Alert.show( "Area: " + box.area() + " volume: " + box. volume() ); Alert.show( "length: " + box.length + " height: " + box. height + "width: " + box.width ); (The above program will not compile, which is what you want. Reflect on why it does not compile and fix it so that it does.)

21 Exercise 2: Private Methods for Box The implementation of area() given in the previous review exercise is probably reasonable for the Box class. But to practice private methods write it like this: function area():Number{ return 2 * faceArea() + 2 * topArea() + 2 * sideArea() ; } In this, faceArea(), topArea(), and sideArea() are private methods that calculate the area of the front face, the top and the side of the box. You will have to add them to your class. Often private methods are "helping" methods that the public methods use, but are not to be used outside the class. Test your program with several versions of the following: var box:Box = new Box( 2.5, 5.0, 6.0 ); Alert.show( "Area: " + box.area() + " volume: " + box. volume() ); Alert.show( "topArea: " + box.topArea() ); (The above program will not compile, as expected.)

22 Exercise 3: Box Constructor and Access Methods Add a new constructor to the Box class: Box(oldBox:Box) This constructor creates a new Box object with identical dimensions as the old Box object. Of course, the old object is not changed. Now add some access methods. An access method is a method that can be used to access the private variables (and other variables) of an object: public length(): Number public height(): Number public width(): Number Each of these methods merely returns the value of one instance variable. Since the object is immutable, there will be no access methods that alter the instance variables.

23 Exercise 4: Bigger Boxes It would be nice to create a box that is bigger than a given box. Write this method: public biggerBox(oldBox:Box):Box This is a public method that returns (evaluates to) a reference to a new Box. The new Box will be 25% larger in each dimension that the old box. The method will have to use a constructor inside of it to create the new box: public biggerBox(oldBox:Box):Box{ return new Box( 1.25*oldBox.width(),...... ) } Now write a method that returns a box that is 25% smaller in every dimension than a given box. As usual, write a testing program that exercises your class.

24 Exercise 5: Nesting Boxes Write a method that evaluates to true or false depending on whether one box completely fits inside another: public fitsInside(outsideBox:Box, insideBox:Box ):Boolean This is potentially a difficult method, since the inside box may fit or not fit depending on how it is rotated. To simplify the method, write it so that it returns true if the two boxes nest without considering rotations (so height is compared to height, length compared to length, and so on.)


Download ppt "ENCAPSULATION. WHY ENCAPSULATE? So far, the objects we have designed have all of their methods and variables visible to any part of the program that has."

Similar presentations


Ads by Google