with java programming object oriented · design: in the object oriented (oo) style ... robustness...

48
Ian Holyer Object Oriented Object Oriented Programming Programming with Java with Java COMSM0103 1

Upload: others

Post on 07-Mar-2020

6 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

Ian Holyer

Object OrientedObject OrientedProgrammingProgramming

with Javawith Java

COMSM0103

1

Page 2: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

ContentsContentsProgramming:Programming: in Java

Design:Design: in the Object Oriented (OO) style

Development:Development: set good examples, avoid bad habits

 

These subjects are big, and they change, so this unit isonly an introduction to start off your lifelong learning

2

Page 3: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

AssumptionsAssumptionsYou have programmed in C (or C++)

You may or may not be a confident programmer

You want to review, consolidate, and extend yourprogramming skills, and learn something about objectorientation, and industry practices

3

Page 4: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

Unit materialsUnit materialsThe unit materials (see csijh.gitlab.io) contain:

lecture notesassignmentsasides, including Java detailsLinks: (SAFE, Java docs, Wrap)

Check frequently, and reload/refresh, for updates

4

Page 5: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

CourseworkCourseworkThere are regular assignments, all individual, some ofwhich will count towards your mark for the unit

There is no exam; the final assignment is open ended,with everyone doing a different mini-project

Early assignments will be at least partly auto-marked;your mark will depend on how many tests you pass

5

Page 6: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

SupportSupportGet support at the timetabled lab sessions

Support each other

See me in my office: things to know about me are

1. I don't use email2. I don't have office hours3. Just drop in (you can check my calendar csijh)

6

Page 7: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

BooksBooksWe won't be following any one book very closely, but Irecommend

Java Programming, at wikibooks, free, Java 7

Thinking in Java, 3rd edition is free, Java 4

My mini Java course in the asides

We will use features from all versions of Java up to 9(but with comments about newer features)

7

Page 8: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

QuestionsQuestionsWhat is Java?

What is OO Programming (OOP)?

What is OO Design (OOD)?

What is OO development?

8

Page 9: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

What is JavaWhat is JavaYou can think of Java as like C, but with:

pointer notation removedother troublesome features removed or changedmuch greater platform independenceclasses and other object oriented features addedlibraries and other development features added

I'll be assuming OpenJDK + OpenJFX (Oracle's JDK is nolonger free, it is almost the same but they charge forsupport)

9

Page 10: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

What type of language?What type of language?C is a procedural (or imperative) language: "do this andthen do that", it uses functionsfunctions and datadata, and functionaldecomposition is its intended design technique

Java is an object oriented language, it uses classes andobjects to organiseorganise functions and data, and objectorientation is its intended design technique

There are other paradigms: assembly languages,scripting languages, declarative languages, functionallanguages, logic languages, ...

10

Page 11: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

Function decompositionFunction decompositionA main function is broken down into smaller functions,etc, forming a tree, with data interwoven everywhere

Although effective programs can be written this way,they tend to be monolithic and brittle

11

Page 12: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

What is OO design?What is OO design?A program is written as independent cooperatingcomponents, each looking after its own data:

It turns out that this scales up better to larger projects,and works better for teams, ifif you do it properly

12

Page 13: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

Importance of OO designImportance of OO designAt first, writing well-designed programs takes moreeffort

Later, it becomes easiereasier to write well-designed programsthan to write poorly designed ones

And it is muchmuch easier to extend, update or re-use well-designed programs

One of the main things that becomes easier is to ensurerobustness

13

Page 14: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

Perfect designsPerfect designsPerfect designs don't existdon't exist

One agile development principle is KISS - Keep It Sweetand Simple, and don't over-engineer

Stop when it worksworks perfectly, don't keep making itprettier inside - perfectionists take note!

A design is always a compromise or tradeoff betweensimplicity, clarity, maintenance, efficiency, generality,compatibility etc.

14

Page 15: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

What is OO development?What is OO development?An OO approach is at the core of today's agiledevelopment practices

We will concentrate mostly on three key issues: whatOO contributes to development, clean programming,and unit testing

When you are doing a group project, it may beenlightening to tie up that experience with the issues inthis unit

15

Page 16: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

Medium level questionsMedium level questionsWhat are classes and objects?

What is abstraction?

What is encapsulation?

What is inheritance?

What is polymorphism?

16

Page 17: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

What are classes and objects?What are classes and objects?Classes are modulesmodules, dividing the source intocomponents, normally with one file per class

Objects are structuresstructures, dividing a running program intocomponents, each holding related data and functions

 

Later, classes and objects will be more than this

17

Page 18: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

Other conceptsOther conceptsClasses and objects provide:

abstraction encapsulation inheritance polymorphism

Think of a car: abstraction = "easy to use, complexinside", encapsulation = "complexity hidden under thehood/bonnet", inheritance = "different models just addfeatures", polymorphism = "tyres fit any make or model"

Follow the links, or read what someone else says

18

Page 19: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

What is abstraction?What is abstraction?Abstraction is concentrating on whatwhat an object does, nothowhow it does it

For the Google Maps program (and some people), a caris a box which gets you from A to B - it just has aposition

In a driving simulator, a car object might haveaccelerate, brake and steer functions

In a self-drive program, a car object has lots of sensorsas well as controls

18a

Page 20: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

What is encapsulation?What is encapsulation?Encapsulation goes further: the internal details of howhowsomething is done cannot be seen, accessed orinfluenced from the outside

One advantage of this is robustness: the user of anobject can't accidentally interfere with its correctworking (it can be misused, but not broken)

Another is maintenance: an object can more easily beupgraded or replaced without changing any code whichuses it (components can be developed independently)

18b

Page 21: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

What is inheritance?What is inheritance?Inheritance is one way of re-using components

A Vehicle component may provide basic operations,shared between child classes Car, Train, Plane, ...

A child component inherits the features and code of itsparent

Beware:Beware: don't over-use inheritance, because it can createa strong dependency between components

18c

Page 22: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

What is polymorphism?What is polymorphism?Polymorphism is another way of re-using components

It is where a component is general enough to be usedfor a wide variety of purposes

It includes generics and overloading

Beware:Beware: although it is essential to know about generictypes in library software, writing your own can bedifficult

18d

Page 23: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

Lower level questionsLower level questionsWhat is Java?

How is it installed?

How are programs compiled?

How are programs run?

19

Page 24: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

Java historyJava historyJava emerged in the 1990s for web applets (nowobsolete) compared with the 1970s for C

It is now used extensively for giant servers, desktopapplications, mobile devices, and embedded processors

It has very little in common with the scripting languagecalled JavaScript, which isn't part of this unit

It has some things in common with C++ but is muchcleaner (C++ is also not part of this unit)

20

Page 25: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

Java effectivenessJava effectivenessPart of Java's success is the fact that it works the sameon every platform, and that its extensive library of re-usable components is part of the standard

Java is almostalmost "write once, run anywhere" (but, e.g.Android's Java is not full Java, yet)

Platform independence comes from the language, thelibrary, and the interpretive bytecode

Interpreting can be slow, but Just-In-Time compilingspeeds it up after an initial pause, and Ahead-Of-Timecompiling is starting to eliminate the initial pause

21

Page 26: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

Java safetyJava safetyPre-compiled machine code ('binary') programs are notsafe; they might do anythinganything to your computer

This is even worse for web applets, where you don't getto choose whether the program runs

Sandboxes were used to make Java safe for the Web(like JavaScript), sandboxes are used on mobiles, andsandboxes are increasingly being used on desktops

Safety depends on JIT or AOT compilation afterafter thesource or bytecode arrives on a computer

22

Page 27: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

Java convenienceJava convenienceThere are no explicit pointers or pointer manipulation(though an understanding of pointers is needed)

There is no explicit memory management (though anunderstanding is needed)

All array accesses have out-of-bound checks

A large set of C problems don't happen, and anotherlarge set cause useful error messages instantly ratherthan causing obscure errors later

23

Page 28: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

Using JavaUsing JavaDetails about installing Java, compiling programs, andrunning them, are in the aside: getting started

The basics are:

edit Program.javaedit Program.java javac Program.java javac Program.java producing Program.classproducing Program.class java -ea Program java -ea Program for testingfor testing java Program java Program for runningfor running

24

Page 29: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

Hello.javaHello.java

Hello WorldHello WorldHere's the traditional minimal program to try out:

classclass HelloHello {{ publicpublic staticstatic voidvoid mainmain(String[] args)(String[] args) {{ System.out.println( System.out.println("Hello World!""Hello World!");); } } }}

class Hello blocks{C} publicstatic main{C} String Systemedit compile run make

See the Java 1 aside for more details on basic syntax

25

Page 30: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

ClassesClassesAlmost always, every file that makes up a program is aclass, and every class is in its own file

classclass HelloHello {{ ... ... }}

You probably won't have to worry about exceptions fora while

A class begins with the keyword class, the class name,then a block containing the data and the code

25a

Page 31: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

Hello.javaHello.java

Class namesClass namesIt is conventional for a class name to start with a capitalletter - if you don't do this, it can cause problems whenprograms are moved from one platform to another

classclass HelloHello {{ ... ... }}

It is conventional for a class name to be the same as thebasename of the file it is in, e.g. class Hello must be ina file Hello.java - if you don't do this, the compilermay be unable to link up the classes properly

25b

Page 32: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

BlocksBlocksThe {C} symbol indicates something that is essentiallythe same as in the C language

In particular, blocks are the same

They are surrounded by curly brackets, and each item isterminated by a semicolon

As in C, blocks used to declare data need a semicolon,whereas normal blocks at the end of statements don't

intint[] list = { [] list = { 11, , 22, , 33 }; }; ifif (n< (n<00) { n = -n; }) { n = -n; }

25c

Page 33: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

publicpublicIf something is declared public, it is visible outsidethe folder the program is in

...... publicpublic ... main ... ... main ... ......

This is needed for main, which must be visible to thesurrounding operating system to run the program

But you won't need it for anything else until you startwriting multi-folder programs

25d

Page 34: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

staticstaticIf something is declared static, it is global ratherthan belonging to an object

... ... staticstatic ... main ... ... main ...

This is needed for main by convention, and you need tounderstand its use in library software (e.g.System.out is a static object)

But you shouldn't use it for anything else, until youunderstand the implications, and the rare circumstanceswhere it should be used

25e

Page 35: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

mainmainAs in C, the program starts in the function called main

... main ...... main ...

But when you run a Java program, you specify whichclass to use, that means there can be main functions inmany classes, and that is useful for testing

The name main is terrible: a function name should be averb, or sometimes an adjective, so run is better - youdon't 'main' a program, you run it!

25f

Page 36: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

StringStringThe type String in Java replaces char * in C

You can tell by the capital letter that it is a class, fullname is java.lang.String (classes in java.langare available to programs without explicit import)

You can read its source code (type 'source String.java'into Google)

Of course, the compiler understands strings andcooperates with the string class, e.g. "Hi" has typeString

25g

Page 37: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

SystemSystemThe System class (java.lang.System) providessome standard facilities, a bit like stdio.h in C

Many of its facilities are static, attached directly to theclass, e.g. System.out for standard output

On the other hand, out is an object, one of manypossible output streams

25h

Page 38: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

EditEditJava can be verbose, but this is offset by (a) the fact thatyou often use the libraries instead of doing it yourselfand (b) you can get your editor to help

For example, if you use Atom as your editor, if you typemain, you will be offered a complete skeleton for themain method as a completion (press Enter to accept)

25i

Page 39: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

CompileCompileTo compile the program, type:

javac Hello.javajavac Hello.java

You mustmust include the extension .java

Compiling produces a file called Hello.classcontaining bytecode ready to run

25j

Page 40: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

RunRunTo run the program, type:

java Hellojava Hello

This time, you must notmust not include an extension

25k

Page 41: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

MakefileMakefile

MakeMakeBecause (a) compiling commands can get complexand/or irritating and (b) the compiler only partiallyhandles dependencies, I suggest using a Makefile fromthe beginning

You can start with this:

%: %.java%: %.java javac [email protected] javac [email protected] java -ea $@ java -ea $@

Then you can adapt it later when you start buildingmulti-class projects

25l

Page 42: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

First assignmentFirst assignmentThe first assignment, this week, is to write a program toturn a mark like 70 into a grade like Distinction

We'll go through the skeleton you've been given for theassignment

26

Page 43: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

ClassesClassesIn Java source programs, a file like Grade.javacontains a class, and each class gets its own file (usually)

classclass GradeGrade {{ ... ... }}

A class begins with the keyword class, the class namewhich must match the file namewhich must match the file name, then a blockcontaining the data and the code

27

Page 44: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

mainmainEvery program has a main function:

publicpublic staticstatic voidvoid mainmain(String[] args)(String[] args) {{ ... ... }}

Unlike C, classes which are supporting modules ratherthan programs can have their own main, often used todo testing. Don't use public or static anywhereelse! (yet)

28

Page 45: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

ObjectsObjects

...Grade program = ...Grade program = newnew Grade(); Grade();

...program.run(args)......program.run(args)...

It is a good idea to get out of the static (C) world as fastas possible

Normal functions like grade, convert, test onlyexist attached to objects

Calling them from each other is normal, it is only inmain that you need the program. prefix

29

Page 46: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

TestsTestsThe main method (function) and the tests are given;just develop grade and convert until the tests pass

Tests are done using assert, a keyword that can beused like a function; it checks that something is true

You need java -ea ('enable assert') to switch ontesting (and some dirty trickery to detect whether ithas been turned on); a Makefile is provided

Note equality testing uses == for ints, but .equals()for strings (the equivalent of strcmp in C)

30

Page 47: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

Checking Checking -ea-eaThe trick is:

booleanboolean ea = ea = falsefalse;; assertassert(ea = (ea = truetrue);); ifif (! ea) System.out.println( (! ea) System.out.println("No -ea flag given!""No -ea flag given!"););

Inside the assert is an assignment (=, notnot ==)

If asserts are not switched on, the assert does nothingand ea is not set to true

30a

Page 48: with Java Programming Object Oriented · Design: in the Object Oriented (OO) style ... robustness 13. Perfect designs Perfect designs don't exist One agile development principle is

Rules of developmentRules of developmentThese are incredibly important for one-file programs, orfor each class in multi-file programs:

keep a program working all the timewrite only one or two lines before re-compilingand re-testingwrite tiny functions, e.g. five linesbuild in automatic tests, run from mainkeep I/O separate and add it lastlastkeep it simple, because it is almost untestable

31