Classes and Objects Encapsulation

Slides:



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

Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
CMSC 202 Inheritance. Aug 6, Object Relationships An object can have another object as one of instance variables. The Person class had two Date.
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.
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)
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
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.
CSCI 1100/1202 April 1-3, Program Development The creation of software involves four basic activities: –establishing the requirements –creating.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
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.
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.
Attribute - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 12/24/2016.
CMSC 202 Classes and Objects. Aug 6, Programming Languages All programming languages provide some form of abstraction Procedural language (eg C)
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-1 Learning Objectives  Classes  Constructors  Principles of OOP  Class type member.
CMSC 202 Polymorphism 2 nd Lecture. Aug 6, Topics Constructors and polymorphism The clone method Abstract methods Abstract classes.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Fall 2013 Chapter 10 Thinking.
XuanTung Hoang 1 Something to discuss Feedbacks on Midterm Exam Final exam and term project  Final exam requires solid knowledge/skills in Java  Be more.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
CSIS 123A Lecture 1 Intro To Classes Glenn Stevenson CSIS 113A MSJC.
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
Structures and Classes
Chapter 10 Thinking in Objects
Classes and Objects: Encapsulation
Polymorphism 2nd Lecture
Chapter 10 Thinking in Objects
Chapter 10 Thinking in Objects
Auburn University COMP 3000 Object-Oriented Programming for Engineers and Scientists Constructors and Other Tools Dr.
Polymorphism 2nd Lecture
Polymorphism 2nd Lecture
Chapter 3: Using Methods, Classes, and Objects
Chapter 4: Writing Classes
Classes and Objects 2nd Lecture
CMSC 202 Static Methods.
CSC240 Computer Science III
CMSC 202 Composition.
Classes and Objects: Encapsulation
Chapter 9 Thinking in Objects
Polymorphism 2nd Lecture
Inheritance I Class Reuse with Inheritance
Chapter 6 Methods: A Deeper Look
CMSC 202 Polymorphism.
CMSC 202 Inheritance.
Encapsulation and Constructors
Learning Objectives Classes Constructors Principles of OOP
Class Reuse with Inheritance
Java Classes and Objects 3rd Lecture
Chapter 9 Thinking in Objects
Java Classes and Objects
CMSC 202 Classes and Objects.
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Chapter 4 Defining Classes I
Classes and Objects Static Methods
Classes, Objects and Methods
OO Programming Concepts
Classes and Objects Reusing Classes with Composition
Information Hiding and Encapsulation Section 4.2
CMSC 202 Encapsulation Version 9/10.
CMSC 202 Exceptions.
Classes and Objects Object Creation
CMSC 202 Constructors Version 9/10.
Presentation transcript:

Classes and Objects Encapsulation CMSC 202 Classes and Objects Encapsulation

Topics Encapsulation Visibility of instance variables and methods Information hiding Visibility of instance variables and methods public private Accessor and mutator methods Private methods Method overloading Aug 6, 2007

OOP Techniques Abstraction Encapsulation Information hiding Discarding details Focus on observable behavior Encapsulation Combines data and operations into a single entity (a class) Focus on implementation Achieved through information hiding Information hiding A form of abstraction Separating the description of how to use a class from the details of the class’ implementation Aug 6, 2007

Types of Programmers In the world of OO program development, it’s convenient to distinguish between Class creators - those developing new classes Client programmers - those who use the classes (a term coined by Scott Meyer) Client programmers want to create applications by using a collection of interacting classes Class creators want to build classes that expose the minimum interface necessary for the client program and hide everything else. Aug 6, 2007

Access Control Access Control Also known as information hiding Provides a boundary for the client programmer Separates interface from implementation A form of abstraction 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 Aug 6, 2007

Access Control in Java Java (and other OOP languages) provide access control to instance variables and methods via visibility modifiers public - accessible by everyone, in particular public members are available to the client programmer. A class interface is defined by its public methods private - accessible only by the methods within the class Others - later Aug 6, 2007

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 print( ) System.out.println(month + “ “ + day + “ “ + year); } // setDate and monthString same as Date1 class Any method may use the class’ private instance variables Aug 6, 2007

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? myDate.print( ); // OK – why? } Aug 6, 2007

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 behaviors July 21, 2008

Encapsulation Definition Combining appropriate methods and data in a single class together with proper access control Aug 6, 2007

The Value of Encapsulation programmers that use a class do not need to know how the class is implemented, only how to use it the information the 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 Aug 6, 2007

Copyright © 2008 Pearson Addison-Wesley. Encapsulation Aug 6, 2007 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 12

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” Aug 6, 2007

Accessors & Mutator In some cases 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 name with get Mutator method changes the value of a private instance variable conventional to start the name of an with set Give the class user indirect access to the instance variables July 21, 2008

More Accessors and Mutators Question: Don’t the use of accessors and mutators defeat the purpose of making the instance variable 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. Aug 6, 2007

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 ( newYear < 1000 || newYear > 9999 ) // this is an invalid year return false; } else year = newYear; return true; // rest of class definition follows Aug 6, 2007

Private Methods Methods may be private Cannot be invoked by the class user Can only be called by other class methods Most commonly used as “helper” methods to support top-down implementation of a public method Aug 6, 2007

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 ) return false; else year = newYear; return true; } // helper method - internal use only private boolean yearIsValid( int year ) return 1000 < year && year < 9999; July 21, 008

More about Methods Many different classes can define a method with the same name (e.g. print). Java can determine which method to call based on the type of the calling object. Consider this code snippet: Date2 birthday = new Date2(); Dog fido = new Dog( ); birthday.print( ); fido.print( ); birthday.print( ) will call the print( ) method defined in the Date2 class because birthday’s type is Date2 fido.print( ) will call the print( ) method defined in the Dog class because fido’s type is Dog Jan 23, 2008

toString One method which should be implemented for all classes is toString. public String toString( ) The toString method returns a String chosen by the class implementer. The string typically contains the values of important instance variables in a readable format. This method is very often used for outputting the “contents” of a class. Jan 23, 2008

Method Overloading Two or more methods in the same class may have the same name. This technique is known as method overloading. Aug 6, 2007

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 ) But suppose we wanted to change only the day and year? We can define another method named setDate like this: public boolean setDate( int day, int year ) (after all, setDate is a good descriptive name for what this method does) Aug 6, 2007

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 // print(), monthString( ), setYear( ), etc. follow Aug 6, 2007

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 ); myDate.print( ); myDate.setDate( 4, 1999 ); } How does Java know which setDate method to call? Aug 6, 2007

Method Signature In Java (and other OO languages), 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) Aug 6, 2007

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

Too Much of a Good Thing Automatic type promotion and overloading can sometimes interact in ways that confuse the compiler. Example: public class X { ... public void printAverage ( int a, double b) //version 1 public void printAverage ( double a, int b) //version 2 } And then consider this: 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 to promote 5 to 5.0 and call the second. The Java compiler is confused and will issue an error stating that the method invocation of myX.printAverage is ambiguous. Aug 6, 2007