57
Basic OO Principles Simple UML Notation CSC 295-01 Spring 2019 Howard Rosenthal

Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Basic OO Principles Simple UML Notation

CSC 295-01Spring 2019

Howard Rosenthal

Page 2: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Course References� Materials for this course have utilized materials in the following documents.

Additional materials taken from web sites will be referenced when utilized.1. http://www.programmedlessons.org/Java9/index.html2. Anderson, Julie and Franceschi Herve, Java Illuminated 5TH Edition,, Jones and

Bartlett, 20193. Bravaco, Ralph and Simonson, Shai, Java programming From The Ground Up,

McGraw Hill, 20104. Deitel, Paul and Deitel, Harvey, Java, How To Program, Early Objects, Tenth

Edition, Pearson Publishing, 20155. Gaddis, Tony, Starting Out With Objects From Control Structures Through

Objects, Pearson Publishing, 20166. Horstmann, Cay, Core Java For The Impatient, Addison Wesley- Pearson

Education, 20157. Schmuller, Joseph, Teach Yourself UML In 24 Hours Second Edition, SAMS

Publishing, 20028. Urma, Raoul-Gabriel, Fusco, Mario and Mycroft, Alan, Java 8 in Action:

Lambdas, Streams, and Functional-Style Programming, Manning Publishing, 2014

9. Wirfs-Brock, Rebecca, Wilkerson, Brian and Wiener, Laura, Designing Object-Oriented Software, Prentice Hall, 1990

2

Page 3: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Lesson Goals

� Review some basic computing and Java concepts� Introduce underlying principles of object-oriented

design� Introduce basic UML class notations

3

Page 4: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

4

Page 5: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

What Can Computer Do?� WWII spurred an interest in machinery that could compute.

� During the war, this interest was stoked by a need to break codes, but also to compute relatively mundane quantities such as the trajectory of an artillery shell.� During WW II women (known as computers) dis much of this

mathematics� This continued after WW II and led to an important role for women in

the early programming at NASA (see movie Hidden Figures)� After the war, interest continued in the abstract notion of

‘computability’. Key computing leaders such as Alan Turing began to wonder what was and wasn’t ‘computable’. � They defined this in an abstract way: � Given an infinite computing power (whatever that is), could they

solve anything? � Are there things that can’t be solved by machines?

5

Page 6: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

What Can Computer Do? – Two Approaches� Maths, maths, maths.

� Ignore the mechanics of any real machine and imagine a hypothetical machine that had infinite computation power, then write some sort of ‘programming language’ for it.

� This language turned out to be a form of mathematics known as ‘Lambda calculus’. � We will be studying lambda implementations in Java

� It was based around the notion of functions in a mathematical sense.� Build it and they will come.

� Understand how to build and use a real computing machine. � This resulted in the von Neumann architecture and the notion of a

Turing machine (basically what we would call a computer).� The four basic elements of a computer are:

� The Central Processing Unit – The CPU� Primary or Random Access Memory (RAM)� Secondary or long term memory – Note: some of these devices are

becoming closer to RAM devices as they are built with solid state circuitry as opposed to spinning electro mechanical parts

� Input and output devices – disks printers, etc.6

Page 7: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

7

The Basic Components of A Computer

� The four basic elements of a computer are:

� The Central Processing Unit – The CPU

� Primary or Random Access Memory (RAM)

� Secondary or long term memory – Note: some of these devices are

becoming closer to RAM devices as they are built with solid state circuitry as opposed to spinning electro mechanical parts

� Input and output devices – disks printers, etc.

Page 8: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Basic Concepts In Computer Software� Operating System – Software that controls all aspects of the computer – DOS,

Windows, MAC OS, UNIX, etc.� Languages and levels of abstraction

� Machine Language – expressed in 0’s and 1’s. This is what the machine understands. A long time ago programmers coded in 0’s and 1’s. It was very hard to write complex programs.

� Assembly Language – A low-level programming language in which a mnemonic is used to represent each of the machine language instructions for a particular computer

Assembly Language Machine LanguageADD 00100101SUB 00010011

� Assembler – The program that translates Assembly Language into Machine Language� Higher Level Languages – Used to write programs in a more understandable form.

Examples include Fortran, C, C++, LISP, Java� Layered Architectures – An approach that allows application programmers to take

advantage of software written by others – i.e. IO drivers, databases, user interfaces, etc. – in order to make the life of the application writer easier

8

Page 9: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Two Programming Paradigms For Higher Level Languages

� Functional Languages.

� These are very mathematically oriented and have the notion of functions as the building blocks of computation.

� FORTRAN – Formula Translation is the most well-known of these early languages

� Originally computers were there to do calculations more quickly

� Imperative or Procedural Languages.

� These have variables (state) and procedures as the main building blocks.

� Such languages are well known—e.g. C—and include what we call object- oriented languages such as C++ and Java.

9

Page 10: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Basic Concepts In Computer Software – Object Oriented Programming

� Original higher level languages were procedural� Good for solving math problems� Little relationship between the data and the operations� Tended to do poorly with higher levels of abstraction

� Object Oriented Programming � Organizes data and operations/processes together into an object.� At the higher level of abstraction we have the Class which is a

description of an object that specifies the types of data values that it can hold and the operations that it can perform � A class is a higher form of a data type� It encapsulates data and methods together

� Classes are instantiated into individual objects

10

Page 11: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Basic Concepts In Computer Software – Compilers and Interpreters� Compilers – Compilers translate source code written in a programming

language into machine language.� Each language has it’s own compiler(s) or interpreters

� Compilers are not machine independent.� Therefore the source code often needed to be tailored based on the capabilities

of the targeted machines. And the output of the compiler was also machine specific

� Java has created an approach that completely separates the source code from the target machine, so the source code can be compiled independently of the machine

� Source code-Data type specifications and instructions written in a high-level programming language

� Object code – A machine language version of source code� In addition to compilers some computer languages use interpreters

� Languages are still at a higher level� Execute directly line by line from the source code� Since interpretation is in real-time some static checking and reliability may be

lost� Slower than directly executing compiled code� Python, Smalltalk, Lisp, some forms of Basic, some scripting languages, etc.

11

Page 12: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Original Compiler Concept� Originally separate compilers were written for each

machine� These compilers produced machine language or assembly

language code for the individual machines� Assembly language code would go through a second

compilation step to produce machine language code

12

12 | Chapter 1: Overview of Programming and Problem Solving

Windows PCC++ compiler

Windows PCmachine language

Windows PCcomputer

UNIX workstation

C++ compilerC++ Code

UNIX workstation

machine language

UNIX workstationcomputer

MacintoshC++ compiler

Macintoshmachine language

Macintoshcomputer

COMPUTEREXECUTESTRANSLATORCODE(COMPILER)

SOURCE CODE(C++)

OBJECTCODE(MACHINELANGUAGEVERSION OFSOURCE CODE)

COMPUTEREXECUTESOBJECTCODE

Figure 1.5 High-level programming languages allow programs to be compiled on different systems.

A benefit of standardized high-level languages is that they allow you to writeportable (or machine independent) code. As Figure 1.5 emphasizes, a single C++ programcan be run on different machines, whereas a program written in assembly language ormachine language is not portable from one computer to another. Because each com-puter family has its own machine language, a machine language program written forcomputer A may not run on computer B.

Visual Basic takes a somewhat different approach than we have described. VisualBasic programs are translated into a standard machinelanguage called Bytecode.

However, there are no computers that actually useBytecode as their machine language. In order for acomputer to run Bytecode programs, it must haveanother program called the Common Language Run-

time (CLR) that serves as a language interpreter for the program. Just as an interpreterof human languages listens to words spoken in one language and speaks a translationof them in a language that another person understands, the CLR reads the Bytecodemachine language instructions and translates them into machine language operationsthat the particular computer executes. Interpretation is done as the program is running,one instruction at a time. It is not the same as compilation, which is a separate step that

Bytecode A standard machine language into whichVisual Basic source code is compiled

Page 13: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Java Is Machine Independent� Java solves the problems of machine dependence. JAVA standardizes

the language and the compiler, which creates bytecode – a form of binary representation. � The bytecode is then presented to a Java Virtual Machine (JVM) which

interprets bytecode exactly the same way regardless of the machine. � This is called Machine Independence.

� The bytecode can be thought of as the machine language of the JVM� The JVM is a virtual machine in software. It has its own machine language.

All Java code is compiled for the JVM� However, bytecode must be interpreted in order to create machine

language instructions that are executed by the physical machine� Oracle typically provides the JVMs for the individual machines

13

Java CompilerSource Code(.java)

Bytecode(.class)

Java VirtualMachine

Machine Language

Target Machine

JVM takes the compiled bytecode and interprets it into the machine code

Page 14: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Java – Pointers and References� A pointer is just the name given to memory addresses when we handle

them in code. � They are very powerful concepts to work with, but you need to take a lot

of care if you start moving things around in memory yourself� Java doesn’t expose pointers to the programmer

� So no pointers, no jumping around in memory, no problem.� Instead Java provides references

� These are like pointers except they are guaranteed to refer to either an object in memory or “null”.

� So if the reference isn’t null, it is valid� Variables are either primitive types or references

� A variable for a reference type holds the memory address. � If you assign something to it a reference variable, what it used to be assigned to

still exists in memory (but your variable doesn’t link to it any more). � Multiple variables can reference the same object in memory

� All objects (created from classes) are accessed through references in Java

� In 121/123 you learned how to pass references to objects to and from methods

14

Page 15: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

15

Page 16: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Overview

16

Page 17: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

What Is Object-Oriented Design And Programming?

� Object-oriented design encourages a view of the world as a system of cooperating and collaborating agents, some of which work sequentially, and other concurrently� First ask what the program is needed to do, not the how� Identify the classes� Instantiate the object and the relationships between the

objects� Hide the implementation but publish the interfaces

� This allows for greater software reuse (i.e. String, Scanner, etc. are examples you are familiar with).

17

Page 18: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Modularity and Classes� Modularity is extremely important in OOP.

� It breaks big problems down into chunks and solve each chunk. � Why modules?

� Modules are conceptually easier to handle� Different people can work on different modules simultaneously � Modules may be re-used in other software projects� Modules can be individually tested as we go (unit testing)

� The modular unit of Java is a class which has both:� State

� Properties that describe that specific instance� E.g. color, maximum speed, value

� Behavior/Functionality – described via methods� Things that it can do� Methods often mutate the state

� E.g. accelerate, brake, turn

18

Page 19: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Graphical Representation Of A Class Using UML

19

Modularity is extremely important in OOP. It’s the usual CS trick:break big problems down into chunks and solve each chunk. In thiscase, we have large programs, meaning scope for lots of coding bugs.We split the program into modules. The goal is:

• Modules are conceptually easier to handle• Di↵erent people can work on di↵erent modules simultaneously• Modules may be re-used in other software projects• Modules can be individually tested as we go (unit testing)

The module ‘unit’ in OOP is a class.

State and Behaviour

An object/class has:

State Properties that describe that specific

instance

E.g. colour, maximum speed, value

Behaviour/Functionality Things that it can do

These often mutate the state

E.g. accelerate, brake, turn

33

Identifying Classes

We want our class to be a grouping of conceptually-related state and behaviour

One popular way to group is using English grammar

Noun → Object

Verb → Method

“The footballer kicked the ball”

Representing a Class Graphically (UML)

MyFancyClass

- age : int

+ SetAge(age: int) : voidBehaviour

State

“+” meanspublic access

“-” meansprivate access

34

Page 20: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Classes and Encapsulation

20

Page 21: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Encapsulation� The act of grouping both data and the operations that affect that

data into a single class/object is known as encapsulation� Another name for encapsulation is information hiding.

� The basic idea is that a class should expose a clean interface that allows interaction, but nothing about its internal state.

� So the general rule is that all state variable should start out as private and only have that access relaxed if there is a very, very good reason� The most standard example is a static class variable, which is almost

always public� Encapsulation helps to minimize coupling between classes.

� High coupling between two class, A and B, implies that a change in A is likely to ripple through to B.

� In a large software project, you really don’t want a change in one class to mean you have to go and fix up the other 200 classes! So we strive for low coupling.

� It’s also related to cohesion. � A highly cohesive class contains only a set of strongly related

functions rather than being a random mix of functionality. � We strive for high cohesion.

21

Page 22: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Encapsulation And UML For An AutoAuto

- model : String- int : milesDriven- double : gallonsOf Gas

+ Auto():+ Auto(String : startModel, int : startMilesDriven, double : startGallonsOfGas):+ getModel() : String+ getMilesDrivenl() : int+ getGallonsOfGas() : double+ setModel(model: String) : void+ setMilesDrivenl(milesDriven: int) : void+ setGallonsOfGas(gallonnsOfGas: double) : void+ milesPerGallon() : double+ toString() : String+ equals(obj: Object) : boolean

22

Notes: + means public- means private# means protected~ is for an internal variableMethods without return variables are constructors (some diagrams don’t use this convention) – constructor(s) still identified by the class nameIf the title or method is italicized it is an abstract class or method

Page 23: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Encapsulation And Information Hiding� Another term that is often associated with encapsulation is information hiding.

� Many programmers regard encapsulation and information hiding as synonyms. � However, object-oriented purists would define encapsulation as the technique

that bundles data and methods into one unit and information hiding as the principle that hides the implementation of a class.

� Giving an instance variable private access has its advantages. � Public access implies that the field is visible and can be changed from any other

program with a simple assignment statement. � This could create unauthorized changes and great confusion.

� Information hiding allows classes to be revised without affecting the code of its clients� In general, information hiding is the principle that hides implementation

details from a client class. When implementation details are hidden, all access to the attributes of a class is through its public methods.

� Remember, classes encapsulate but classes do not necessarily enforce information hiding. � Restricting access within a class affords information hiding.

23

Page 24: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Aggregation

24

Page 25: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Aggregation Allows Us To Build Realistic Models� Aggregation occurs when an instance of a class is a field in another class

� In real life, objects are frequently made of other objects. � A house, for example, is made of door objects, window objects, wall objects, and much

more. � It is the combination of all these objects that makes a house object.

� When designing software, it sometimes makes sense to create an object from other objects. � For example, suppose you need an object to represent a course that you are

taking in college. You decide to create a Course class, which will hold the following information:� Course name� Instructor� Textbook

� The last two of these items are classes in there own right� You could put fields for each of these items in the Course class. � However, a good design principle is to separate related items into their own

classes. � In this example, an Instructor class could be created to hold the instructor-

related data and a TextBook class could be created to hold the textbook-related data. Instances of these classes could then be used as fields in the Course class.

25

Page 26: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

A UML Envisioning Of A Course

26

8.7 Aggregation 525

Aggregation in UML DiagramsYou show aggregation in a UML diagram by connecting two classes with a line that has an open diamond at one end. The diamond is closest to the class that is the aggregate. Figure 8-14 is a UML diagram that shows the relationship among the Course, Instructor, and TextBook classes. The open diamond is closest to the Course class because it is the aggregate (the whole).

Figure 8-14 UML diagram showing aggregation

Security Issues with Aggregate ClassesWhen writing an aggregate class, you should be careful not to unintentionally create “secu-rity holes” that can allow code outside the class to modify private data inside the class. We will focus on the following two specific practices that can help prevent security holes in your classes:

r� Perform Deep Copies When Creating Field Objects An aggregate object contains references to other objects. When you make a copy of

the aggregate object, it is important that you also make copies of the objects it refer-ences. This is known as a deep copy. If you make a copy of an aggregate object, but only make a reference copy of the objects it references, then you have performed a shallow copy.

Page 27: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

The “has-a” Associations in UML

� Arrow going left to right says “a College has zero or more students”

� Arrow going right to left says “a Student has exactly 1 College”

� What it means in real terms is that the College class will contain a variable that somehow links to a set of Student objects, and a Student will have a variable that references a College object.

� Note that we are only linking classes: we don't start drawing arrows to primitive types.

27

The “has-a” Association

College Student1 0...*

Arrow going left to right says “a College has zero or more students”

Arrow going right to left says “a Student has exactly 1 College”

What it means in real terms is that the College class will contain a variable that somehow links to a set of Student objects, and a Student will have a variable that references a College object.

Note that we are only linking classes: we don't start drawing arrows to primitive types.

The graphical notation used here is part of UML (Unified ModelingLanguage). UML is basically a standardised set of diagrams thatcan be used to describe software independently of any programminglanguage used to create it.

UML contains many di↵erent diagrams (touched on in the SoftwareDesign course). Here we just use the UML class diagram such as theone in the slide.

35

Anatomy of an OOP Program (Java)

public class MyFancyClass {

public int someNumber;public String someText;

public void someMethod() {

}

public static void main(String[] args) {MyFancyClass c = new

MyFancyClass();}

}

Class name

Class state (properties that an object has such as colour or size)

Class behaviour (actions an object can do)

'Magic' start point for the program (named main by convention)

Create an object of type MyFancyClass in memory and get a reference to it

There are a couple of interesting things to note for later discussion.Firstly, the word public is used liberally. Secondly, the main functionis declared inside the class itself and as static. Finally there is thenotation String[] which represents an array of String objects in Java.You will see arrays in the practicals.

36

Page 28: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Inheritance

28

Page 29: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

What Is Inheritance?

� Object oriented languages have a feature called inheritance, that enables you to define new classes based upon an existing class. � The new classes are similar to the existing class, but have

additional member variables and methods. � This makes programming easier because you can build

upon an existing class instead of starting out from scratch.

� Inheritance is part of the reason for the enormous success of modern software.

� Programmers are able to build upon previous work and to continuously improve and upgrade existing software.

29

Page 30: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Why Inheritance?� Before object oriented programming if you had the source code

for a class, you could copy the code and change it to do what you wanted.

� This approach had two major problems:� It was hard to stay organized.

� Say that you already have several dozen classes which you need to keep and that you need additional classes based on the original ones.

� Also, say that you need several classes based on the new classes. � You will end up with dozens of source files which are all versions of other

source files that have been changed in various ways. � Now say that a bug has been found in one of the source files.

� Some source files based on it need fixing; others, perhaps not. � Without careful planning you will end up with an disorganized,

inconsistent, buggy mess. You needed to study the original code. � Say that you have a complicated class that basically does what you

want, but you need a small modification. � If you edit the source code, even to make a small change, you risk

breaking something. � So you must study the original code to be sure that your changes are

correct which may not be easy.30

Page 31: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Basic Principles Of Inheritance� A common form of reuse of classes is inheritance.� We can organize classes into hierarchies of

functionality.� The class at the top of the hierarchy (superclass)

defines instance variables and methods common to all classes in the hierarchy.

� We derive a subclass, which inherits behavior and fields from the superclass.

31

Page 32: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Java and Inheritance� The class that is used to define a new class is called a

parent class (or superclass or base class.) The class based on the parent class is called a child class (or subclass or derived class.)

� In diagrams, the arrow points from the child to the parent.� In Java, (unlike with humans) children inherit

characteristics from just one parent. � This is called single inheritance.

� Some languages allow a child to inherit from more than one parent. � This is called multiple inheritance. � With multiple inheritance, it is sometimes hard to tell which

parent contributed what characteristics to the child (as with humans).

� Java avoids these problems by using single inheritance.

32

Page 33: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

A Few Common Synonyms� There are three sets of phrases for describing

inheritance relationships:� parent / child� base class / derived class� superclass / subclass

� Programmers use all three sets interchangeably.

33

Page 34: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Two Simple Questions (1)� Can a parent class have more than one child class?� Can a parent class inherit characteristics from its child

class?

34

Page 35: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Two Simple Questions (2)� Can a parent class have more than one child class?

� Yes, a parent can have any number of children. But child can have only one parent.

� Can a parent class inherit characteristics from its child class?� No. Inheritance goes in only one direction.

35

Page 36: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Objects And Classes (1)� The picture shows a parent class and a child

class, and some objects that have been constructed from each. These objects are shown as rectangles.

� In the picture, "Joe's car," "Mary's Ford," and "Bob's Ford" represent objects. � The cloudy classes represent designs, not objects.

� Objects are constructed as a program runs. An object is constructed by following a description in a class file that was created by compiling a Java source program.

� How many types of automobile are there in the diagram?

� How many automobile objects are there in the diagram?

36

Page 37: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Objects And Classes (2)� How many types of automobile are there in the

diagram?� 2

� How many automobile objects are there in the diagram?� 3

37

Page 38: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Hierarchies (1)

� We can organize classes into hierarchies of functionality.

� The class at the top of the hierarchy (superclass) defines instance variables and methods common to all classes in the hierarchy.

� We derive a subclass, which inherits behavior and fields from the superclass.

38

Page 39: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Hierarchies (2)

� This picture shows a hierarchy of classes. It shows that "Ford is-a automobile," "Nissan is-a automobile," and that "VW is-a automobile." It also shows that "Sentra is-a Nissan."

� In a hierarchy, each class has at most one parent but might have several children classes. The class at the top of the hierarchy has no parent. This class is called the root of the hierarchy.

39

Page 40: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Visualizing A Simple Hierarchy In UML

� In UML diagrams, arrows point from the subclass to the superclass.

40

Page 41: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Superclasses and Subclasses

� A superclass can have multiple subclasses.� Subclasses can be superclasses of other subclasses.� In Java a subclass can inherit directly from only one

superclass.� All classes in Java inherit from the Object class, a special

class at the top of the hierarchy.� A big advantage of inheritance is that we can write code

that is common to multiple classes once and reuse it in subclasses.� A subclass can define new instance variables and methods,

some of which may override (hide) those of a superclass.

41

Page 42: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Abstract Classes

42

Page 43: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

What Is An Abstract Class

� We have learned that classes in a hierarchy are related by the is-a relationship. � For example, a Nissan is-a Automobile, and a Sentra is-a

Nissan.

� Java has features that allow programs to establish and work with hierarchies. Much of the power of object oriented programming comes from this.

� An abstract class is a class that cannot be instantiated but that can be the parent of other classes. � This is useful when you have a broad concept (like

Automobile) but actual objects must be specific types (like Sentra).

43

Page 44: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

A Sample Card Hierarchy

44

Page 45: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Abstract Classes� An abstract class in Java is a class that is never instantiated.

� Its purpose is to be a parent to several related classes. � The children classes inherit from the abstract parent class.� It is defined like this:abstract class ClassName{

. . . . . // definitions of methods and variables}

� Access modifiers such as public can be placed before abstract.

� Even though it can not be instantiated, an abstract class defines methods and variables that children classes inherit, as we will shortly describe

45

Page 46: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Abstract Methods� An abstract method has no body.

� It declares an access modifier, return type, and method signature followed by a semicolon.

� It has no statements.� A non-abstract child class inherits the abstract method and must

define a non-abstract method that matches the abstract method.� Abstract classes can (but don't have to) contain abstract

methods. � Also, an abstract class can contain non-abstract methods, which

will be inherited by the children.� An abstract child of an abstract parent does not have to define

non-abstract methods for the abstract signatures it inherits. � This means that there may be several steps between an abstract

base class to a child class that is completely non-abstract. (You don’t need to define each method the first step down.

46

Page 47: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Why Use Abstract Classes

� Abstract classes are used to organize programs. � Of course the same program can be

organized in many ways. � Our example program could be written

without an abstract class. � But a real-world application might have

hundreds of classes. Grouping classes together is important in keeping a program organized and understandable.

� The advantage of using an abstract class is that you can group several related classes together as siblings. The picture shows this program after its object has been constructed.

47

Page 48: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Multiple Classes From A Single Abstraction� We can create multiple classes from a single abstraction,

and then create objects from any of those classes� Remember – You can’t instantiate an object from an

abstract class

48

Page 49: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Polymorphism

49

Page 50: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

What Is Polymorphism?

� An important concept in inheritance is that an object of asubclass is also an object of any of its superclasses.

� That concept is the basis for an important OOP feature called polymorphism.� Polymorphism means "having many forms." � In Java, it means that one variable might be used with several

objects of related classes at different times in a program.� Polymorphism simplifies the processing of various objects

in the same class hierarchy because we can use the same method call for any object in the hierarchy using a superclass object reference.

50

Page 51: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Using Polymorphism

To use polymorphism, these conditions must be true:� The classes are in the same hierarchy.� All subclasses override the same method(s).� A subclass object reference is assigned to a superclass

object reference. � The superclass object reference is used to call the

overridden method.

51

Page 52: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

What Are Descendants?

� What types of objects can a reference variable refer to?� A variable can hold a reference to an object whose class

is a descendant of the class of the variable.� A descendant of a class is a child of that class, or a child

of a child of that class, and so on. � Siblings are not descendants of each other

� You don’t inherit anything from your brother or sister!

52

Page 53: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Interfaces

53

Page 54: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

Why Interfaces� As we have discussed, Java has single inheritance, only.

� This means that a child class inherits from only one parent class and usually this is all you need.

� However, sometimes multiple inheritance would be convenient, where a child class inherits characteristics from several parent classes.

� But this can be confusing. What happens when two parents have different versions of the same method?

� With object oriented programming, you define software objects that mimic "real world" objects. � This makes programs easier to think about and more reliable. � In the real world, you often think about an object in several different

ways. � You can think of your car as a vehicle or as taxable property. � It would be convenient if software objects, also, could be thought of

in several ways. � But a Java object belongs to just one class.

� Interfaces give Java some of the advantages of multiple inheritance without the disadvantages.� The use of interfaces is especially useful with graphics applications.

54

Page 55: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

What Is An interface In Java (1)

� An interface describes aspects of a class other than those that it inherits from its parent.

� An interface is a set of requirements that the class must implement.

� An interface is a list of constants and method headers. � The methods are not implemented in the interface

(there is no method body). � A class that implements an interface must implement all

of the methods listed in the interface.

55

Page 56: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

What Is An interface In Java (2)� As we have said, a class can extend one parent class to inherit the

methods and instance variables of that parent. � A class can also implement an interface to gain additional

methods and constants. � However, the methods in the interface must be implemented

(explicitly written) as part of the importing class definition. � The interface is a list of requirements that the class definition must

explicitly meet (through written code, not through inheritance).� For example, a class Car might extend the Vehicle class.

� Inheritance then gives it all the methods and instance variables of Vehicle.

� If Car also implements the Taxable interface, then its definition must contain code for all the methods listed in Taxable.

56

Page 57: Lesson 2 - Basic OO Principles Simple UML Notation CSC 295 ...€¦ · We will be studying lambda implementations in Java It was based around the notion of functions in a mathematical

An interface Is A Contract

� When a class implements an interface, it is agreeing to provide all of the methods that are specified by the interface.

� It is often said that an interface is like a “contract,” and when a class implements an interface it must adhere to the contract.

57