Encapsulation COMP 401, Fall 2014 Lecture 06 9/4/2014.

Slides:



Advertisements
Similar presentations
Object Oriented Programming
Advertisements

Final and Abstract Classes
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
Classes and Object- Oriented... tMyn1 Classes and Object-Oriented Programming The essence of object-oriented programming is that you write programs in.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Immutable Objects and Classes.
Road Map Introduction to object oriented programming. Classes
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
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)
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 Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
CS 2511 Fall  Abstraction Abstract class Interfaces  Encapsulation Access Specifiers Data Hiding  Inheritance  Polymorphism.
Classes and Class Members Chapter 3. 3 Public Interface Contract between class and its clients to fulfill certain responsibilities The client is an object.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Packages. Package A package is a set of related classes Syntax to put a class into a package: package ; public class { …} Two rules:  A package declaration.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
07 Coding Conventions. 2 Demonstrate Developing Local Variables Describe Separating Public and Private Members during Declaration Explore Using System.exit.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
CS200 Algorithms and Data StructuresColorado State University Part 4. Advanced Java Topics Instructor: Sangmi Pallickara
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
Inheritance Extending Class Functionality. Polymorphism Review Earlier in the course, we examined the topic of polymorphism. Many times in coding, we.
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,
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
23-Oct-15 Abstract Data Types. 2 Data types A data type is characterized by: a set of values a data representation, which is common to all these values,
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Procedural and Object-Oriented Programming 13.1.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 4 – August 30, 2001.
Comp 249 Programming Methodology Chapter 13 Interfaces & Inner Classes Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
CSSE501 Object-Oriented Development. Chapter 4: Classes and Methods  Chapters 4 and 5 present two sides of OOP: Chapter 4 discusses the static, compile.
Exceptions, cont’d. Factory Design Pattern COMP 401 Fall 2014 Lecture 12 9/30/2014.
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.
CSci 162 Lecture 10 Martin van Bommel. Procedures vs Objects Procedural Programming –Centered on the procedures or actions that take place in a program.
GoodOO Programming Practice in Java © Allan C. Milne v
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Introduction to Object-Oriented Programming Lesson 2.
Data Design and Implementation. Definitions Atomic or primitive type A data type whose elements are single, non-decomposable data items Composite type.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Introduction to Classes and Objects Starting Out with C++ Early.
Classes, Interfaces and Packages
Object Oriented Programming. OOP  The fundamental idea behind object-oriented programming is:  The real world consists of objects. Computer programs.
Presented by Ted Higgins, SQL Server DBA An Introduction to Object – Oriented Programming.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
CS/ENGRD 2110 FALL 2013 Lecture 3: Fields, getters and setters, constructors, testing 1.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
Part 1: Composition, Aggregation, and Delegation Part 2: Iterator COMP 401 Fall 2014 Lecture 10 9/18/2014.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Fall 2013 Chapter 10 Thinking.
Mr H Kandjimi 2016/01/03Mr Kandjimi1 Week 3 –Modularity in C++
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
CSCI 383 Object-Oriented Programming & Design Lecture 15 Martin van Bommel.
Computer Programming II Lecture 5. Introduction to Object Oriented Programming (OOP) - There are two common programming methods : procedural programming.
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
OOP: Encapsulation &Abstraction
Phil Tayco Slide version 1.0 Created Sep 18, 2017
Chapter 10 Thinking in Objects
Chapter 10 Thinking in Objects
INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING (OOP) & CONCEPTS
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Chapter 9 Thinking in Objects
Chapter 9 Thinking in Objects
Chapter 14 Abstract Classes and Interfaces
Final and Abstract Classes
Lecture 8 Object Oriented Programming (OOP)
Presentation transcript:

Encapsulation COMP 401, Fall 2014 Lecture 06 9/4/2014

Picking up from last time… Abstraction – Defining a class to represent an abstraction – Instance fields hold object state – Instance methods define functions / procedures associated with the abstraction

Motivating Encapsulation Consider lec6.v1 What’s the danger?

Principle of Encapsulation Do not expose the internal state of an object directly. – Protects object fields from being put into an inconsistent or erroneous state. – Avoids situation in which external code is dependent on this specific implementation. Or said another way: allows for the implementation of an abstraction to be improved/changed without breaking other code. Separate “exposed” behavior from “internal” behavior – Exposed behavior Procedures / functions other objects / code expected to interact with. – Internal behavior Procedures / functions defined only for use by methods that are part of the class.

Encapsulation In Practice Part 1: Do Not Expose Internal State Make all fields private – Amend field declaration with “private” access modifier. Provide public methods that retrieve and/or alter properties – Methods that retrieves a property is called a “getter”. – Methods that set a property is called a “setter” Benefits – Can support “read-only” fields by NOT providing a setter – Setter can validate new value to prevent misuse or illegal values. – Can define derived or complex properties that are actually related to multiple field values.

JavaBeans Conventions JavaBeans – Software engineering framework Associated tools – Relies on code following certain conventions In particular, getters and setters for object properties. Given type T and property P: – Signature of a getter: public T getP() – Signature of a setter: public void setP(T value)

lec6.v2 Provides getters for x and y values of a Point, but not setters. – Ensures Point is immutable Provides getters and setters for point of a Triangle Notice effect on original code in main method in Lec6Ex1.java

Setter Validation Setters should validate their values if possible. – One of the advantages of providing access to properties only through methods. Illegal / improper values should cause a runtime exception like this: throw new RuntimeException(“Explanation string”);

lec6.v3 Adds equals method to Point for comparison. setA(), setB(), and setC() in Triangle validate by… – making sure that points are distinct – checking for co-linearity Added area() method Added check_colinearity() method – Notice that I’ve chosen a specific precision for the check based on area.

Derived Properties Property that is a combination or transformation of object state fields. – Can you recognize two of these already in Triangle? Same principle for getters and setters applies here. – If using JavaBeans conventions, name methods with proper form and signature. – Read-only properties should not have a setter. – Setters should validate if necessary.

lec6.v4 Changed area() and perimeter() to getArea() and getPerimeter() to follow JavaBeans conventions. – What about individual side lengths? Could have done the same, but didn’t to make another point later on. Created getPoints() and setPoints() as derived properties for dealing with all three points at once as an array.

Using Fields Internally Marking a field as “private” prevents access from code outside of the class. – But notice that there is no restriction to access private fields between different instances. – Look at distanceTo() and equals() methods in Point Does this violate principle of encapsulation? – Gray area Could argue no since code is within the class. Could argue yes since access to other point’s state is outside the context of the this reference. – My advice Always safe to use exposed getter / setter, so do so. There are sometimes good reasons not to, but generally these are related to issues of performance and optimization.

lec6.v5 Re-wrote distanceTo() and equals() using getters for x and y values

Encapsulation In Practice Part 2: Separate Exposed Behavior Define an “interface” for all exposed behavior – In Java, an interface is like a contract. Indicates that a certain set of public methods are available. One or more classes can indicate that they implement the interface. – Name of interface can be used as a type name Just like class names are used as type names. Value of an interface type variable can be set to any object that is an instance of a class that implements the interface.

Interfaces in Java Like classes, should go in their own.java file – Should have same name as file – Body of interface is a just list of method signatures. Implementing classes MUST declare these methods as public Form: interface InterfaceName { type method1(parameters); type method2(parameters); // etc… } Classes specify which interfaces they implement with “implements” modifier as in: class ClassName implements InterfaceA, InferfaceB {

Interface Naming Conventions Interface name must be different from class names that implement the interface. Convention A – Start all interface names with “I” for interface. For example: ITriangle, Ipoint – Class names can be anything that is not in this form. Convention B – Use generic abstraction name for interface. – Make class names descriptive of implementation If no natural way to do this, simply append “Impl” to generic abstraction name to differentiate. Personally, I generally go with convention B.

lec6. v6 Separates Point into an interface and an implementing class. – Notice that distanceTo() and equals() are part of behavior I want the abstraction to expose. Notice that main method uses variables with type Point (the interface name), but that the actual object is created as an instance of a specific class that implements the interface Point. Notice that Triangle only interacts with the methods specified in the Point interface.

Advantage of Encapsulation Can provide different implementations of the same behavior – lec6.v7 Create a new implementation of Point based on polar coordinates.

Exposed vs Internal Behavior Exposed behavior should be reflected in the interface(s) that a class implements – Recall that any method declared in an interface must be defined by an implementing class as a public method. Internal behavior should be hidden – Use private modifier on these methods to ensure that access only occurs within the class

lec6.v8 Continued application of encapsulation principle to Triangle by… – … defining Triangle as an interface – … rewriting what used to be the class Triangle as the class PointTriangle that implements the interface – … hiding internal behaviors as private methods