Information Hiding and Encapsulation

Slides:



Advertisements
Similar presentations
Intro to CS – Honors I More Objects and Methods GEORGIOS PORTOKALIDIS
Advertisements

Based on Java Software Development, 5th Ed. By Lewis &Loftus
Functions ROBERT REAVES. Functions  Interface – the formal description of what a subprogram does and how we communicate with it  Encapsulation – Hiding.
Object Oriented Design An object combines data and operations on that data (object is an instance of class) data: class variables operations: methods Three.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Copywrite 2003 Walter Savitch These slides are for the exclusive use of students in CSE 11 at UCSD, Winter quarter They may not be copied or used.
1 Chapter 7 Functions Dale/Weems/Headington. 2 Functions l Control structures l every C++ program must have a function called main l program execution.
Copywrite 2003 Walter Savitch These slides are for the exclusive use of students in CSE 11 at UCSD, Winter quarter They may not be copied or used.
1 Fall 2007ACS-1903 Chapter 6: Classes Classes and Objects Instance Fields and Methods Constructors Overloading of Methods and Constructors Scope of Instance.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Understanding class definitions Looking inside classes.
COMP 110 Information Hiding and Encapsulation Tabitha Peck M.S. February 25, 2008 MWF 3-3:50 pm Philips
Ranga Rodrigo. Class is central to object oriented programming.
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.
Programming With Java ICS201 University Of Ha’il1 Chapter 8 Polymorphism and Abstract Classes.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
The Java Programming Language
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
SWE 510: Object Oriented Programming in Java1 Defining Classes 1 This slide set was compiled from the Absolute Java textbook and the instructor’s own class.
Classes CS 21a: Introduction to Computing I First Semester,
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
FIRST JAVA PROGRAM. JAVA PROGRAMS Every program may consist of 1 or more classes. Syntax of a class: Each class can contain 1 or more methods. public.
CPS120: Introduction to Computer Science Functions.
Static Methods. 2 Objectives Look at how to build static (class) methods Study use of methods calling, parameters, returning values Contrast reference.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
JAVA Classes Review. Definitions Class – a description of the attributes and behavior of a set of computational objects Constructor – a method that is.
CSSE501 Object-Oriented Development. Chapter 4: Classes and Methods  Chapters 4 and 5 present two sides of OOP: Chapter 4 discusses the static, compile.
Day Class Definitions and Methods Local & global variables, parameters & arguments,
Designing Classes Prelude © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures and Abstractions with Java, 4e Frank.
CSC 142 D 1 CSC 142 Instance methods [Reading: chapter 4]
Chapter 41 Defining Classes and Methods Chapter 4.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void.
CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, Stack and Heap When your program is running, some memory is used to store local variables.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
Defining Classes I Part B. Information hiding & encapsulation separate how to use the class from the implementation details separate how to use the class.
COMP Information Hiding and Encapsulation Yi Hong June 03, 2015.
Prof. I. J. Chung Data Structure #1 Professor I. J. Chung.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Defining Classes and Methods
More Sophisticated Behavior
Working with Java.
Software Development Java Classes and Methods
Chapter 3: Using Methods, Classes, and Objects
About the Presentations
COS 260 DAY 10 Tony Gauvin.
Classes and Objects 2nd Lecture
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
Computer Science II Exam 1 Review.
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.
Chapter 3 Introduction to Classes, Objects Methods and Strings
Classes, Objects, and Methods
Defining Classes and Methods
Announcements Program 2 is due tomorrow by noon Lab 4 was due today
Defining Classes and Methods
Defining Classes and Methods
Classes CS 21a: Introduction to Computing I
Defining Classes and Methods
Information Hiding and Encapsulation Section 4.2
Introduction to Computer Science and Object-Oriented Programming
Presentation transcript:

Information Hiding and Encapsulation

Information Hiding A programmer using a method that you have defined does not need to know the details of the code in the body of the method. This simplifies the work of the programmer using your method(s). Designing a method so that it can be used without any need to understand the detail of the code is called information hiding.

Precondition and Postcondition Comments The precondition for a method states the conditions that must be true before the method is invoked. The postcondition describes the effect of the method invocation. It tells what will be true after the method is executed assuming that the precondition is true. For a method that returns a value, the postcondition describes the value returned. For a void method, the postcondition describes changes to the calling object

Example of Precondition and Postcondition Comments /** Precondition: The instance variables of the calling object have values. Postcondition: the data stored in (the instance variables of) the calling object have been written to the screen. */ public void writeOutput()

Another Example of Precondition and Postcondition Comments /** Precondition: years is a nonnegative number. Postcondition: Returns the projected population of the calling object after the specified number of years. */ public int projectedPopulation(int years)

Assertion Checks An assertion is something that says something about the state of your program. An assertion can be either true or false. If there are no mistakes in your program, it should be true. Preconditions and postconditions are examples of assertions.

Assertion Checks (cont’d) You can have assertion comments at other places in your code besides the beginning or the end. For example all the comments in the following code are assertions. //n == 1 while (n < limit) { n = 2*n; } //n >= limit //n is the smallest power of 2 >= limit.

Assertion Checks (cont’d) In Java, instead of just inserting comments about assertions, you can insert an assertion check statement that will stop the program if the condition is false. Such a statement has the form: assert Boolean Expression; If you compile and run your program in the proper way, the assertion check statement will stop your program if the condition is false. If it is true nothing happens.

Assertion Checks (cont’d) We can replace two of the comments in the previous example with assertion statements. assert n == 1; while (n < limit) { n = 2*n; } assert n >= limit; //n is the smallest power of 2 >= limit.

Assertion Checks (cont’d) The comment: //n is the smallest power of 2 >= limit. cannot easily be replaced with an assertion statement; so we leave it as a comment. In order for assertion statements to be recognized and executed, your program must be compiled using the following command line statement: javac –source 1.5 YourProgram.java

Assertion Checks (cont’d) To run the program with assertion checking turned on, enter the following command: java –enableassertions YourProgram If you run your program in the normal way, assertion checking is turned off, and all assert statements are ignored.

The Public and Private Modifiers It is considered good programming practice to make all instance variables private. Whenever you place the modifier private before an instance variable, that instance variable’s name is not accessible outside of the class definition. Only methods within the class can access instance variables that are declared to be private.

The Public and Private Modifiers (cont’d) This does not mean that you cannot change the values of private instance variables from outside the class where they are declared. It only means that you must invoke a method from within the class to set or change values of instance variables. This means, of course, that the class must have methods to accomplish this.

The Public and Private Modifiers (cont’d) In the SpeciesThirdTry class example, readInput is an example of such a method. SpeciesThirdTry xSpecies = new SpeciesThirdTry(); //Valid xSpecies.readInput(); //Valid xSpecies.name = “Aardvark”; //Invalid System.out.println(xSpecies.population); //Invalid System.out.println(xSpecies.growthRate); //Invalid Methods can also be private, so methods like readInput must be public.

Accessor and Mutator Methods All instance variables should be private, and accessor and mutator methods should be provided for accessing and setting or changing values of instance variables from outside their class. A public method that reads and returns data from one or more private instance variables is called an accessor method.

Accessor and Mutator Methods (cont’d) Names of accessor methods typically begin with get. A public method that changes the data stored in one or more private instance variables is called a mutator method. Names of mutator methods typically begin with set.

Example of a Mutator Method public void set(String newName, int newPopulation, double newGrowthRate) { name = newName; if (newPopulation >= 0) population = newPopulation; else System.out.println( “ERROR: using a negative population.”); System.exit(0); } growthRate = newGrowthRate;

Example of Accessor Methods public String getName(); { return name; } public String getPopulation(); return population; public String getGrowthRate(); return growthRate;

Encapsulation This is the process of hiding all of the details of a class definition to make using the class easier. When done correctly, a class can be divided into two parts, the user interface and the implementation. The implementation consists of all the private instance variables of a class and the definitions of all the methods, both public and private.

Encapsulation (cont’d) The user interface consists of all the headings for the public methods and defined constants of the class, along with comments that tell a programmer how to use these public methods and public defined constants. When a class is defined in a way that conceptually separates the user interface and the implementation we say that the class is well encapsulated.

Guidelines for Defining a Well-Encapsulated Class Place a comment before the class definition that describes how the programmer should think about the class data and methods. Declare all instance variables in the class to be private. Provide public accessor and mutator methods to read and change data in an object of the class and any other methods a programmer may need to manipulate data in the class, e.g., input and output methods.

Guidelines for Defining a Well-Encapsulated Class (cont’d) Fully specify how to use each public method with a comment placed before the method heading. Make any helping methods (methods to be used only by other methods of the class) private. Place all user interface comments (those that describe how to use the class or method of the class) before the class definition and before public method definitions. A general rule is to use /* */ comments for user interface comments and // comments for implementation comments.

Automatic Documentation with javadoc javadoc is a tool that automatically generates user interface documentation for your classes. javadoc extracts comments and other information from your classes to provide the information necessary for someone to use your program, but the usefulness of the documentation depends, in part, on the usefulness of the comments you place in your code.

UML Class Diagrams Class diagrams are normally created before the class is defined. They provide a guide to the programmer in implementing the code necessary to solve the problem at hand. A minus sign before an instance variable or method indicated that it is private. A plus sign means that it is public.

UML Class Diagram Example Purchase name: String groupCount: int groupPrice: double numberBought: int + setName(String newName): void + setPrice(int count, double costForCount): void + setNumberBought(int number): void + readInput( ): void + writeOutput( ): void + getName( ): String + getTotalCost( ): double + getUnitCost( ): double + getNumberBought( ): int