CMPT 225 - PowerPoint PPT Presentation

1 / 41
About This Presentation
Title:

CMPT 225

Description:

Mutable and Immutable Objects. The data of an immutable object cannot be changed e.g. ... Be careful when changing the data of a mutable object if ... – PowerPoint PPT presentation

Number of Views:26
Avg rating:3.0/5.0
Slides: 42
Provided by: johne78
Category:
Tags: cmpt | mutable

less

Transcript and Presenter's Notes

Title: CMPT 225


1
CMPT 225
  • Object Oriented Programming

2
OOP Principles
  • Encapsulation
  • Color Class
  • Designing Classes
  • Inheritance
  • Polymorphism

3
Representing Colour
  • Let's say we need to represent colours
  • There are many different colour models
  • One such is the RGB (red green blue) model
  • RGB colours
  • A colour is represented by three numbers, which
    represent the amount of red, green and blue
  • These values are sometimes recorded as doubles
    (between 0.0 and 1.0) or sometimes as
  • Integers, between 0 and 255 (or some other
    number)
  • How many colours can be represented?

4
Colours and rgb Values
255,0,0
128,128,192
0,255,0
255,128,0
0,0,255
0,0,0
255,255,255
128,128,128
5
Storing Colour Data
  • Three variables are required to represent one
    colour
  • It would be convenient to be able to refer to
    colours in the same way that we refer to
    primitive types
  • Object Oriented Programming (OOP) allows classes
    and objects to be used to organize code to
    collect variables and methods that represent one
    entity
  • An object is a collection of variables and
    methods
  • A class is a factory (or blueprint) for creating
    objects of a particular type

6
Encapsulation
  • An object combines both variables and methods in
    the same construct
  • Variables give the structure of an object
  • Methods dictate its behaviour
  • A class should be a cohesive construct that
    performs one task (or set of related tasks) well
  • Objects can be used as if they were primitive
    types
  • To encapsulate means to encase or enclose
  • Each object should protect and manage its own
    information, hiding the inner details
  • Objects should interact with the rest of the
    system only through a specific set of methods
    (its public interface)

7
Classes and Objects
  • The class sets out what data and operations are
    required
  • For colours these include
  • Values for red, green and blue for a colour
  • And methods to access these values and create new
    colours
  • Think of the class being a factory or a
    blueprint, and the objects being the manufactured
    from the class
  • An individual object is an instance of a class
  • Similar to the way that a variable is of a type
  • Each object has its own space in memory, and
    therefore each object has its own state
  • Individual Color objects represent individual
    colours, each with their own values for red,
    green and blue

8
Objects and Software Design
  • Using objects can aid design
  • People are used to the idea of everyday objects
    having states and behaviours
  • The same idea can be applied to components of a
    program
  • Using objects can also promote modular design
    where modules are
  • Highly cohesive (they perform one well defined
    task) and
  • Loosely coupled classes are as independent as
    possible from each other which makes it easier
    to
  • to understand one class without having to read
    others
  • maintain classes because changes to the
    implementation of one class can be made without
    affecting other classes

9
Information Hiding
  • To achieve loose coupling, classes (and modules)
    should only be allowed to communicate through
    their interfaces, thereby hiding their
    implementations details
  • Loose coupling decreases the likelihood that
    changing the implementation of one module will
    require major changes in other modules
  • Provides protection of the details from other
    modules, e.g. prevents other modules from
    assigning invalid values to a module's attributes
  • Information hiding can easily be achieved in
    object oriented programming

10
Designing a Class
  • There are many ways to design a class
  • Is its major purpose to store data? or
  • To perform some operation? or
  • A combination of the two?
  • Your initial focus may either be on the class
    variables or its methods
  • There are, however, some general principles of
    good design

11
Design Make Variables Private
  • Variables should generally by made directly
    inaccessible from outside the class
  • This is achieved by making them private
  • The values of variables can be accessed using
    getter methods (or accessors)
  • A getter method returns the value of a variable
  • New values can be assigned to variables using
    setter methods (or mutators)
  • A setter method assigns the value passed to its
    parameter to a variable

12
Design Write Constructors
  • Constructors should initialize all of the
    variables in an object
  • It is often necessary to write more than one
    constructor
  • Default constructor, with no parameters that
    assigns default values to variables
  • Constructor with parameters for each variable,
    that assigns the values passed to the parameters
    to those variables
  • Copy constructor that takes an object of the same
    class and creates a copy of it

13
Design Make Helper Methods Private
  • Helper methods are methods that assist class
    methods in performing their tasks
  • Helper methods are often created to implement
    part of a complex task or to
  • Perform sub-tasks that are required by a number
    of the class other methods
  • They are therefore only useful to the class and
    should not be visible outside the class
  • Helper methods are relevant only to the
    implementation of a class, therefore they should
    be hidden, and not made part of the interface

14
Design Setters Only When Needed
  • Remember that variables are made private to hide
    implementation details from other classes
  • To prevent classes from depending on each others'
    implementations and
  • To protect variables from being assigned
    inappropriate values
  • Providing a setter method to a variable may allow
    some other class to change the variable
    inappropriately
  • Therefore, consider whether or not each variable
    requires a setter method

15
Mutable and Immutable Objects
  • The data of an immutable object cannot be changed
    e.g.
  • Strings - it is not possible to change the
    characters in a string
  • The data of mutable can be changed e.g.
  • Points
  • Collection objects
  • Be careful when changing the data of a mutable
    object if
  • It is referred to by more than one variable or
  • If it is contained in a collection, particularly
    a set or a map

16
static variables and methods
  • static variables and methods belong to the
    class, not individual objects
  • They are shared by all objects of the same class
  • Static variables are often used to store class
    constants
  • Or keep track of data that relates to the entire
    class
  • There is only one copy of a static variable for
    the entire class
  • They may be changed by static or non-static
    methods
  • Static methods cannot access the variables of
    individual object
  • As it would not be possible to determine which
    object's variables to change

17
non static variables and methods
  • If a variable or method is not given the static
    modifier then it is non-static and belongs to
    individual objects
  • Non-static variables are used to store data about
    individual objects
  • e.g. the characters of one string or the
    coordinates of one Point
  • They cannot be changed or accessed by non-static
    methods
  • Non-static methods can access either static or
    non-static variables (or methods)
  • When accessing non-static variables they refer to
    the variables that belong to the calling object

18
Inheritance
19
Inheritance
  • Inheritance is a relationship between classes
    whereby one class can derive the behaviour and
    structure of another class
  • The base (or parent) class is called the
    superclass
  • The derived class is called the subclass
  • Inheritance allows the programmer to capture
    hierarchies that exist in a problem domain and
  • To specialize an existing class thereby
    increasing the reusability of existing code
  • e.g Swing in Java where subclassing Swing
    components is encouraged

20
Inheritance Fundamentals
  • Subclasses inherit the variables and methods of
    their superclass
  • That is, subclasses have access to all of the
    public superclass variables and methods without
    including them in the definition of the subclass
  • Additional variables and methods can be defined
    for subclasses
  • Superclass methods can be overwritten in the
    subclass
  • That is, a subclass may include its own
    definition of a method that exists in the
    superclass

21
Relationships Between Classes
  • When designing new classes from existing classes
    it is important to identify the relationship
    between the classes
  • We can identify three basic types of relationship
  • is-a relationships
  • e.g. a graduate student is a student
  • has-a relationships
  • e.g. a ball has a color
  • as-a relationships
  • e.g. a stack is implemented as a list

22
Inheritance is-a Relationships
  • Public inheritance should only be used when an
    is-a relationship exists between the base and the
    derived class e.g.
  • A Ball is a Sphere, so a Ball class could be
    derived from a Sphere class, however
  • A Color is not a Ball (!!) so a Color class
    should not be derived from a Ball class (or vice
    versa)
  • In programming terms a derived class should be
    type-compatible with all of its ancestor classes
  • That is, an instance of a derived class can be
    used instead of an instance of the base class
  • But not necessarily the other way around

23
Designing Class Hierarchies
  • There is an important principle in software
    design for writing code that is easy to maintain
    and re-use
  • This is the Open-Closed principle
  • Software entities like classes, modules and
    functions should be open for extension but closed
    for modifications
  • In terms of classes, this means that creating a
    subclass should not necessitate changing the
    superclass
  • Any subclass should comply with the Liskov
    Substitution Principle or it may also violate the
    Open-Closed Principle

24
Liskov Substitution Principle
  • The supertypes behaviour must be supported by
    the subtypes subtype objects can be substituted
    for supertype objects without affecting the
    behaviour of the using code.
  • This property is referred to as the substitution
    principle. It allows using code to be written in
    terms of the supertype specification, yet work
    correctly when using objects of the subtype.
  • from Program Development in Java, Barbara
    Liskov

25
LSP Violation Example
  • in class

26
What is a is-a relationship?
  • The key is that an is-a relationship should apply
    to the behaviour of objects, not to the
    real-world entities that the objects are modeling
  • A square is a rectangle but
  • The behaviour of a Square object is not
    consistent with the behaviour of a Rectangle
    object
  • The test, therefore, is that a subclass public
    behaviour should conform to the expected
    behaviour of its base class
  • This is important because a client program may
    depend (or expect) that this conformity exists

27
Polymorphism
28
Polymorphism
  • Polymorphism means many forms
  • A Subclass definition can include a redefinition
    of a superclass method
  • The subclass method then overrides the superclass
    method
  • If the calling object is a subclass object, the
    subclass version of the method is used
  • This is useful if the subclass is required to
    perform the same action but in a different way
  • Note that overriding is not the same as
    overloading
  • An overloaded method is one where there is
    another method with the same name, but a
    different parameter list

29
Dynamic Binding
  • The correct version of an overridden method is
    decided at execution time, not at compilation
    time, based on the type to which a pointer refers
  • This is known as dynamic binding or late binding
  • This allows a superclass reference to be used to
    refer to a subclass object while still eliciting
    the appropriate behaviour
  • If a method of the subclass overrides a
    superclass method the subclass method will still
    be used
  • Based on the object type rather than the pointer
    type

30
Java Classes
31
Creating Objects Constructors
  • To create a new object it is necessary to use a
    special method called a constructor and the new
    operator
  • Color c1 new Color(125, 67, 212)
  • Color c2 new Color(0, 255, 0) //green
  • The constructor has the same name as the objects
    class and may require input (arguments)
  • Many classes (such as Color) have a number of
    different constructors
  • There are a couple of notable exceptions where it
    is not necessary to explicitly use the new
    operator and a constructor
  • New arrays can be created using an initialization
    list
  • Strings can be created by specifying the string
    literal to be created.

32
Using the Methods of an Object
  • Once an object has been created the dot operator
    can be used to access its methods
  • e.g. To find the green component of some Color
    object c
  • int g c.getGreen()
  • Methods are not limited to accessing data about
    an object
  • Some methods will change objects or create new
    objects
  • The Color.brighter() method returns a new,
    brighter, version of the calling Color (without
    changing the calling Color )
  • Color brightC c.brighter()

33
Java and the Default Constructor
  • If no constructor exists for a class Java creates
    a default constructor
  • Which assigns default values to each variable
  • Primitive typed variables are assigned the
    default values (e.g. 0 for numeric types)
  • Reference variables are assigned null
  • Creating any constructor (including constructors
    with parameters) prevents this default from being
    created

34
Inheritance in Java
  • Java uses the keyword extends to indicate that
    one class is a subclass
  • e.g. class Student extends Person
  • The subclass inherits the methods and variables
    of the superclass
  • Subclasses do not have special access to
    superclass methods or variables
  • Use super.x() to access (public) methods
  • Multiple inheritance is not allowed

35
Java and Dynamic Binding
  • In Java, all object variables are references to
    objects and all objects are created dynamically
  • A base class reference variable that refers to a
    subclass object will use the subclass methods
  • But does not have access to subclass methods that
    do not exist in the base class
  • Containers that store a base class can be used to
    store subclass objects
  • When retrieving objects from such a container the
    subclass specific methods can be accessed by
    first casting the object to a subclass reference
  • Note that all Java classes are subclasses of
    Object

36
C Classes
37
C Header Files
  • Every C class should be divided into header and
    implementation files
  • The header (.h) file should contain
  • Class definition (class keyword and class name)
  • Class variables
  • Method declarations (not definitions) for
  • Constructors, a destructor, getters and setters
    as necessary, and any other methods that are
    required
  • The class should be divided into public and
    private sections as necessary
  • The implementation (.cpp) file should contain the
    definition of each method declared in the header
    file
  • The method name must be preceded by the class
    name and
  • e.g. int MyClassgetMyVariable()

38
C Constructors
  • If no constructor exists for a class C creates
    a default constructor
  • Creating any constructor (including constructors
    with parameters) prevents this default from being
    created
  • If no copy constructor exists C creates one
  • The compiler created copy constructor performs a
    shallow copy
  • It only copies the values of data members which,
    for pointers, are addresses, so it will not
    create a copy of dynamically allocated data
  • If the class uses dynamically allocated memory a
    copy constructor that performs a deep copy must
    be written to copy any such dynamically allocated
    data

39
C Destructors
  • Every C class must have a destructor which is
    responsible for destroying a class instance
  • MyClass() //destructor for the MyClass class
  • A class can have only one destructor
  • C automatically creates a destructor for a
    class if one has not been written
  • If a class does not use dynamically allocated
    memory it can depend on the compiler generated
    destructor
  • Otherwise a destructor must be written to
    deallocate any memory that has been dynamically
    allocated by the class
  • By using delete to deallocate memory associated
    with an object

40
Inheritance in C
  • C specifies inheritance in the class
    declaration
  • e.g. class Student public Person
  • Note that classes can use public, private or
    protected inheritance
  • Public - public and protected members of the base
    class remain public and protected members of the
    subclass
  • Protected - public and protected members of the
    base class are protected members of the subclass
  • Private - public and protected members of the
    base class are private members of the subclass
  • Multiple inheritance is allowed in C, but is
    not recommended!

41
Static and Dynamic Binding
  • Unlike Java, C object variables are not
    pointers unless explicitly declared so, therefore
    a C object variable uses static memory
  • Declaring a pointer to an object allows it to be
    assigned the address of a new object, which is
    created using memory that is dynamically
    allocated
  • During their lifetime base class pointers may
    refer to subclass objects whose address has been
    assigned to them
  • If the subclass has overridden methods of the
    base class the subclass method will be used only
    if
  • The calling object is a subclass object variable
    (not a pointer) or
  • The calling object is a subclass object and the
    call is made via a subclass pointer or
  • The calling object is a subclass object and the
    call is made via a base class object and the base
    class (overridden) method has been declared as
    virtual
Write a Comment
User Comments (0)
About PowerShow.com