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.

Slides:



Advertisements
Similar presentations
Fields, Constructors, Methods
Advertisements

CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
Abstract Data Types Data abstraction, or abstract data types, is a programming methodology where one defines not only the data structure to be used, but.
Road Map Introduction to object oriented programming. Classes
Access to Names Namespaces, Scopes, Access privileges.
Starting Classes and Methods. Objects have behaviors In old style programming, you had: –data, which was completely passive –functions, which could manipulate.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
Slides prepared by Rose Williams, Binghamton University Chapter 13 Interfaces and Inner Classes.
25-Jun-15 Starting Classes and Methods. Objects have behaviors In old style programming, you had: data, which was completely passive functions, which.
1 Classes, Encapsulation, Methods and Constructors Class definitions Scope of Data –Instance data –Local data The this Reference Encapsulation and Java.
Classes, Encapsulation, Methods and Constructors
Terms and Rules Professor Evan Korth New York University (All rights reserved)
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
1 Lecture 4 Objects and Classes Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Writing Classes (Chapter 4)
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Week 4 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
PART 3. You have been using static methods in your programs before and methods are the building blocks of procedural programming. In this part of the.
Question of the Day  On a game show you’re given the choice of three doors: Behind one door is a car; behind the others, goats. After you pick a door,
Chapter 2 Introducing Interfaces Summary prepared by Kirk Scott.
Encapsulation, Inheritance & Polymorphism. OOP Properties Encapsulation ­The process of creating programs so that information within a class is not accessible.
Java Software Solutions Lewis and Loftus Chapter 4 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects and Classes -- Introduction.
Comp 249 Programming Methodology Chapter 13 Interfaces & Inner Classes Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Chapter 4 Writing Classes Part 2. © 2004 Pearson Addison-Wesley. All rights reserved4-2 Classes A class can contain data declarations and method declarations.
CSSE501 Object-Oriented Development. Chapter 4: Classes and Methods  Chapters 4 and 5 present two sides of OOP: Chapter 4 discusses the static, compile.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
Programming in Java CSCI-2220 Object Oriented Programming.
© 2004 Pearson Addison-Wesley. All rights reserved September 12, 2007 Encapsulation ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
Introduction to Generics
CS0007: Introduction to Computer Programming Classes: Documentation, Method Overloading, Scope, Packages, and “Finding the Classes”
CSCI 1100/1202 April 1-3, Program Development The creation of software involves four basic activities: –establishing the requirements –creating.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Copyright © 2002 W. A. Tucker1 Chapter 10 Lecture Notes Bill Tucker Austin Community College COSC 1315.
OOP with Java, David J. Barnes/Eric Jul Defining Classes1 Object State and Complexity Objects maintain a state. State is represented by a set of attributes.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Programming in java Packages Access Protection Importing packages Java program structure Interfaces Why interface Defining interface Accessing impln thru.
Object Oriented Programming. OOP  The fundamental idea behind object-oriented programming is:  The real world consists of objects. Computer programs.
1 Classes, Encapsulation, Methods and Constructors Class definitions Scope of Data –Instance data –Local data The this Reference Encapsulation and Java.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Topics Instance variables, set and get methods Encapsulation
OOP Basics Classes & Methods (c) IDMS/SQL News
Chapter 3 Implementing Classes
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
Understanding class definitions Exploring source code 6.0.
CUSTOM OOP. SYNTAX OF A CLASS DEFINITION Class definitions (descriptions) look like this: class ClassName { Descriptions of the instance variables and.
DESIGNING CLASSES. SPECIFICATIONS FOR THE CAR CLASS Professional programmers carefully design the classes they need before any coding is done. With well-
CSCI 51 Introduction to Programming Dr. Joshua Stough February 26, 2009.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
Classes (Part 1) Lecture 3
Review: Two Programming Paradigms
Chapter 3: Using Methods, Classes, and Objects
Chapter 5 Classes.
CS240: Advanced Programming Concepts
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Encapsulation & Visibility Modifiers
Ch 4: Writing Classes Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: Classes and Objects.
Outline Anatomy of a Class Encapsulation Anatomy of a Method
CSG2H3 Object Oriented Programming
Presentation transcript:

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 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.

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

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 < ) 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.

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.

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() ); }

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.

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.

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.

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.

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 } }

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.

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.

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.

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.

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.

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.

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

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()

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.)

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.)

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.

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.

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.)