Classes and Objects: Encapsulation

Slides:



Advertisements
Similar presentations
Based on Java Software Development, 5th Ed. By Lewis &Loftus
Advertisements

Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Immutable Objects and Classes.
ECE122 L6: Problem Definition and Implementation February 15, 2007 ECE 122 Engineering Problem Solving with Java Lecture 6 Problem Definition and Implementation.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William Loftus.
Encapsulation CMSC 202. Types of Programmers Class programmers – Developers of new classes – Goal: Expose the minimum interface necessary to use a new.
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.
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
1 Chapter 8 – Classes and Object: A Deeper Look Outline 1 Introduction 2 Implementing a Time Abstract Data Type with a Class 3 Class Scope 4 Controlling.
JAVA Classes Review. Definitions Class – a description of the attributes and behavior of a set of computational objects Constructor – a method that is.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
CSCI 1100/1202 April 1-3, Program Development The creation of software involves four basic activities: –establishing the requirements –creating.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
CMSC 202 Classes and Objects: The Basics. Version 9/09 2 Programming & Abstraction All programming languages provide some form of abstraction. –Also called.
AP Computer Science A – Healdsburg High School 1 Unit 9 - Why Use Classes - Anatomy of a Class.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
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.
CMSC 202 CMSC 202, Advanced Section Classes and Objects In Java.
Defining Classes I Part B. Information hiding & encapsulation separate how to use the class from the implementation details separate how to use the class.
OOP Basics Classes & Methods (c) IDMS/SQL News
CMSC 202 Classes and Objects. Aug 6, Programming Languages All programming languages provide some form of abstraction Procedural language (eg C)
CSE 501N Fall ‘09 03: Class Members 03 September 2009 Nick Leidenfrost.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Fall 2013 Chapter 10 Thinking.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Lecture 3: Introduction to Object and Classes Michael Hsu CSULA.
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
Chapter 10 Thinking in Objects
Lecture 3: Introduction to Object and Classes
Classes and Objects: Encapsulation
Phil Tayco Slide version 1.0 Created Sep 18, 2017
Chapter 10 Thinking in Objects
Chapter 4: Writing Classes
Chapter 10 Thinking in Objects
Inheritance and Polymorphism
Chapter 3: Using Methods, Classes, and Objects
Chapter 4: Writing Classes
Classes and Objects 2nd Lecture
CMSC 202 Static Methods.
CSC240 Computer Science III
Object Based Programming
Chapter 5 – Writing Classes
Chapter 9 Thinking in Objects
Classes and Objects Encapsulation
Encapsulation and Constructors
Outline Writing Classes Copyright © 2012 Pearson Education, Inc.
Learning Objectives Classes Constructors Principles of OOP
Java Classes and Objects 3rd Lecture
Defining Classes I Part A.
Chapter 9 Thinking in Objects
Defining Classes and Methods
CS100J Lecture 7 Previous Lecture This Lecture Java Constructs
Java Classes and Objects
CMSC 202 Classes and Objects.
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Classes and Objects Static Methods
CMSC202 Computer Science II for Majors Lecture 07 – Classes and Objects (Continued) Dr. Katherine Gibson Based on slides by Chris Marron at UMBC.
Chapter 9 Objects and Classes
OO Programming Concepts
Classes and Objects Reusing Classes with Composition
CMSC 202 Encapsulation Version 9/10.
Classes and Objects Object Creation
Chapter 7 Objects and Classes
CMSC 202 Constructors Version 9/10.
Presentation transcript:

Classes and Objects: Encapsulation CMSC 202 Classes and Objects: Encapsulation

Types of Programmers Class creators Client programmers those developing new classes want to build classes that expose the minimum interface necessary for the client program and hide everything else Client programmers those who use the classes (a term coined by Scott Meyer) want to create applications by using a collection of interacting classes Version 9/09

OOP Techniques Class creators achieve their goal through encapsulation. Encapsulation: Combines data and operations into a single entity (a class) Provides proper access control Focuses on implementation Achieved through information hiding (abstraction) Version 9/09

The Value of Encapsulation Client programmers do not need to know how the class is implemented, only how to use it. The information the client programmer needs to use the class is kept to a minimum. Class implementation may be changed with no impact on those who use the class. Version 9/09

Access Control Encapsulation is implemented using access control. Separates interface from implementation Provides a boundary for the client programmer Visible parts of the class (the interface) can be used and/or changed by the client programmer. Hidden parts of the class (the implementation) Can be changed by the class creator without impacting any of the client programmer’s code Can’t be corrupted by the client programmer Version 9/09

Access Control in Java Visibility modifiers provide access control to instance variables and methods. public visibility - accessible by everyone, in particular the client programmer A class’ interface is defined by its public methods. private visibility - accessible only by the methods within the class Others - later Version 9/09

Date2 Class public class Date2 { In this new date class, the instance variables have been labeled private. public class Date2 { private String month; private int day; private int year; public void toString( ) return month + “ “ + day + “ “ + year; } // setDate and monthString same as Date1 class Any Date2 class method may use the class’ private instance variables. Version 9/09

Access Control Example Date1 class - public instance variables were used Date2 class - private instance variables are now used public class Date2Demo { public static void main( String[ ] args ) { Date2 myDate = new Date2( ); myDate.month = “July”; // compiler error myDate.day = 4; // compiler error myDate.year = 1950; // compiler error myDate.setDate( 7, 4, 1950 ); // OK – why? System.out.println( myDate.toString( )); } Version 9/09

Private Instance Variables Private instance variables are only usable within the class. Private instance variables hide implementation details, promoting encapsulation. Private instance variables are not accessible by the client programmer (class user). Good programming practice: Label all instance variables as private. The class has complete control over how/when/if the instance variables are changed. Instance variables primarily support class behavior. Version 9/09

Encapsulation Summary Combine methods and data in a single class. Use private instance variables for information hiding. Minimize the class’ public interface. “Keep it secret, keep it safe.” Version 9/09

Accessors & Mutator Class behavior may allow access to, or modification of, individual private instance variables. Accessor method retrieves the value of a private instance variable conventional to start the method name with get Mutator method changes the value of a private instance variable conventional to start the name of the method with set Gives the client program indirect access to the instance variables. Version 9/09

More Accessors and Mutators Question: Doesn’t the use of accessors and mutators defeat the purpose of making the instance variables private? Answer: No The class implementer decides which instance variables will have accessors. Mutators can: validate the new value of the instance variable, and decide whether or not to actually make the requested change. Version 9/09

Date2 Accessor and Mutator public class Date2 { private String month; private int day; // 1 - 31 private int year; // 4-digit year // accessors return the value of private data public int getDay ( ) { return day; } // mutators can validate the new value public boolean setYear( int newYear ) { if ( 1000 <= newYear && newYear <= 9999 ) year = newYear; return true; } else // this is an invalid year return false; // rest of class definition follows Version 9/09

Accessor/Mutator Caution In general you should NOT provide accessors and mutators for all private instance variables. Recall that the principle of encapsulation is best served with a limited class interface. Too many accessors and mutators lead to writing procedural code rather than OOP code. More on this later. Version 9/09

Private Methods Methods may be private. Cannot be invoked by a client program Can only be called by other methods within the same class definition Most commonly used as “helper” methods to support top-down implementation of a public method Version 9/09

Private Method Example public class Date2 { private String month; private int day; // 1 - 31 private int year; // 4-digit year // mutators should validate the new value public boolean setYear( int newYear ) { if ( yearIsValid( newYear ) ) year = newYear; return true; } else // year is invalid return false; // helper method - internal use only private boolean yearIsValid( int year ) return 1000 <= year && year <= 9999; Version 9/09

More About Methods Different classes can define a method with the same name. Java can determine which method to call based on the type of the calling object. Example: Date2 birthday = new Date2( ); Dog fido = new Dog( ); System.out.println(birthday.toString( )); System.out.println(fido.toString( )); birthday.toString( ) will call the toString( ) method defined in the Date2 class because birthday’s type is Date2. fido.toString( ) will call the toString( ) method defined in the Dog class because fido’s type is Dog. Version 9/09

Method Overloading Two or more methods in the same class may also have the same name. This technique is known as method overloading. Version 9/09

public boolean setDate( int month, int day, int year ) Overloaded setDate The Date2 class setDate method: public boolean setDate( int month, int day, int year ) Suppose we wanted to change only the day and year? Define another method named setDate: public boolean setDate( int day, int year ) (After all, setDate is a good descriptive name for what this method does.) Version 9/09

Date3 Class - Overloaded setDate Method public class Date3 { private String month; private int day; // 1 - 31 private int year; // 4 digits public boolean setDate( int newMonth, int newDay, int newYear ) // code here } public boolean setDate( int newDay, int newYear ); // code here, doesn’t change month // toString( ), monthString( ), setYear( ), etc. follow Version 9/09

Date3Demo Class How does Java know which setDate method to call? public class Date3Demo { public static void main (String[ ] args) Date3 myDate = new Date3( ); myDate.setDate( 1, 23, 1982 ); System.out.println( myDate.toString( ) ); myDate.setDate( 4, 1999 ); } How does Java know which setDate method to call? Version 9/09

Method Signature A method is uniquely identified by its name and its parameter list (parameter types and their order). This is known as its signature. Examples: public boolean setDate(int newMonth, int newDay, int newYear) public boolean setDate(String newMonth, int newDay, int newYear) public boolean setDate(int newDay, int newYear) public boolean setDate(int newDay, String newMonth) Version 9/09

Return Type is Not Enough Suppose we attempt to overload Date3’s setDay() method by using different return types. public void setDay( int day ) { /* code here */ } public boolean setDay( int day ) { /* code here */ } This is NOT valid method overloading because the code that calls setDay( ) can ignore the return value. birthday.setDay( 22 ); The compiler can’t tell which setDay( ) method to call. Just because a method returns a value doesn’t mean the caller has to use it. Version 9/09

Too Much of a Good Thing Automatic type promotion and overloading can sometimes interact in ways that confuse the compiler. Example: public class X { //version 1 public void printAverage ( int a, double b) {/*code*/} //version 2 public void printAverage ( double a, int b) {/*code*/} } And then consider this: X myX = new X( ); myX.printAverage( 5, 7 ); The Java compiler can’t decide whether to promote 7 to 7.0 and call the first version of printAverage, or promote 5 to 5.0 and call the second. Version 9/09