Presentation on theme: "Introduction to Java 2 Programming"— Presentation transcript:
1 Introduction to Java 2 Programming Lecture 1Java, Principles of OO, UML
2 Overview Introducing Java Principles of Object Oriented Programming Key features of the languagePrinciples of Object Oriented ProgrammingWhat is OOP? Why is it important?Basic principles and advantagesThe Unified Modelling LanguageUML Class Diagrams
3 Some History Developed and maintained by Sun Microsystems Originally called OakAimed at producing an operating environment for networked devices and embedded systems…but has been much more successfulDesign objectives for the languageSimple, object-oriented,Distributed, multi-threaded, and platform neutralRobust, secure, scaleableWhen Java was produced as an independent language, it was envisaged that it would help revolutionise the web, providing more dynamic features to web pages, e.g. animation, more complex user interfaces, etc. However its actually had more success as a server-side development language rather than for applets or desktop application development. That’s not to say it can’t do those things, and do them well, but it’s a niche that its occupies very well due to a number of features.Dynamic web pages are now typically the realm of Macromedia Flash and similar tools.
4 The Virtual Machine Java is both compiled and interpreted Source code is compiled into Java bytecodeWhich is then interpreted by the Java Virtual Machine (JVM)Therefore bytecode is machine code for the JVMJava bytecode can run on any JVM, on any platform…including mobile phones and other hand-held devicesNetworking and distribution are core featuresIn other languages these are additional APIsMakes Java very good for building networked applications, server side components, etc.
5 Features of the JVM The Garbage Collector Java manages memory for you, the developer has no control over the allocation of memory (unlike in C/C++).This is much simpler and more robust (no chance of memory leaks or corruption)Runs in the background and cleans up memory while application is runningThe Just In Time compiler (JIT)Also known as “Hot Spot”Continually optimises running code to improve performanceCan approach the speed of C++ even though its interpretedThese two features provide some big advantages. Memory management can be error prone. Memory leaks are often difficult to diagnose properly (or even identify). Anyone who has worked with C/C++ is likely to have encountered these problems.The JIT provides a task that the developer would otherwise have to do manually: profile the code to determine the performance critical sections. While this is still worthwhile, the basic JIT compiler in the JVM provides a good head-start. Again profiling is a tricky task as performance bottlenecks are never where you expect. Because the JVM has complete knowledge of what an application does, its in a position to adjust the code to provide some basic tuning.This means performance testing a Java application needs to allow time for the JIT to kick in. Typically see slower performance early on, which then improves before reaching a plateau.
6 Features of the JVM Security Class Loading Java offers very fine control over what an application is allowed to doE.g. Read/write files, open sockets to remote machines, discover information about the users environment, etcUsed in Java Applets to create a “sandbox”. Stops a rogue applet attacking your machine.Makes Java very safe, an important feature in distributed systemsClass LoadingLoading of bytecode into the virtual machine for executionCode can be read from a local disk, over a network, or the InternetAllows downloading of applications and applets on the fly…and even ‘mobile code’
7 Versions of Java Java Language vs Java Platform Current version of the language is 1.4.1Core language plus additional APIs is called the Java 2 platformThree versions of the Java 2 Platform, targetted at different usesJava 2 Micro Edition (J2ME)Very small Java environment for smart cards, pages, phones, and set-top boxesSubset of the standard Java libraries aimed at limited size and processing powerJava 2 Standard Edition (J2SE)The basic platform, which this course will coverJava 2 Enterprise Edition (J2EE)For business applications, web services, mission-critical systemsTransaction processing, databases, distribution, replication
8 The Java APIs Sun are constantly adding new features and APIs The Core Java API is now very largeOften difficult to keep up with every changeSeparate set of extension APIs for specific purposesE.g. Telephony, Web applications, Game programmingAll new developments reviewed through Java Community Process (Chance for developers to provide feedback on emerging standards and APIsUseful to keep an eye on what's coming throughAlso a wide range of “open source“ APIs availableE.g. through the Jakarta project (
9 Useful Resources Useful resources on the web Java home (Articles, Software and document downloads, TutorialsJava Developer ServicesEarly access downloads, forums, newsletters, bug databaseJavaworld (Java magazine site, good set of articles and tutorialsIBM developerWorks (Technology articles and tutorials
10 Principles of Object Oriented Programming Introducing JavaKey features of the languagePrinciples of Object Oriented ProgrammingWhat is OOP?Why is it important?The Unified Modelling LanguageUML Class Diagrams
11 Object-Oriented Programming Understanding OOP is fundamental to writing good Java applicationsImproves design of your codeImproves understanding of the Java APIsThere are several concepts underlying OOP:Abstract Types (Classes)Encapsulation (or Information Hiding)AggregationInheritancePolymorphismThere are two ways to approach Java. Either as just another language, I.e. begin with the basic syntax and show how procedural programs can be created, and then teach OO concepts later on. Or you begin with the OO concepts and introduce the syntax along the way.I prefer the latter approach, which this course will take, because understanding OOP is critical to working well with Java. You can only get the most from the language by understanding these features.OOP has several key concepts which we’ll review now, but will investigate in more detail as we learn more about the Java language. At this point we’re just introducing some of the basic terminology.
12 What is OOP? Modelling real-world objects in software Why design applications in this way?We naturally classify objects into different types.By attempting to do this with software aim to make it more maintainable, understandable and easier to reuseIn a conventional application we typically:decompose it into a series of functions,define data structures that those functions act uponthere is no relationship between the two other than the functions act on the dataOO modelling isn’t only about representing real-world objects, but it’s a useful working definition.Contrast functional decomposition versus OOP. Note that many languages have added “object based”Features so these are extreme views, but should illustrate the main differences.
13 What is OOP? How is OOP different to conventional programming? Decompose the application into abstract data types by identifying some useful entities/abstractionsAn abstract type is made up of a series of behaviours and the data that those behaviours use.Similar to database modelling, only the types have both behaviour and state (data)Note that this is reminiscent of database modelling: we identify the entities that we want to model and then define their attributes. Here we go a step further and identify the behaviours that those entities should have so we can use that data.
14 Abstract Data TypesIdentifying abstract types is part of the modelling/design processThe types that are useful to model may vary according to the individual applicationFor example a payroll system might need to know about Departments, Employees, Managers, Salaries, etcAn E-Commerce application may need to know about Users, Shopping Carts, Products, etcObject-oriented languages provide a way to define abstract data types, and then create objects from themIt’s a template (or ‘cookie cutter’) from which we can create new objectsFor example, a Car class might have attributes of speed, colour, and behaviours of accelerate, brake, etcAn individual Car object will have the same behaviours but its own values assigned to the attributes (e.g. 30mph, Red, etc)In Java an abstract type is known as a class.
15 Note that there’s no relationship between data and functions Note that there’s no relationship between data and functions. Data may be reused in several places, so each function has to have knowledge of that data, e.g. what types it contains, where its stored, etc, etc.In an OO model each object maintains its own data. The functions and data are “fused” into an abstract data type.Note that this is more manageable as I can change the structure of any piece of data, e.g. integer to floating point, add/remove new pieces of information without impacting any of the rest of the application. It’s what helps make OO systems more reusable.
16 EncapsulationThe data (state) of an object is private – it cannot be accessed directly.The state can only be changed through its behaviour, otherwise known as its public interface or contractThis is called encapsulation
17 Encapsulation Main benefit of encapsulation Internal state and processes can be changed independently of the public interfaceLimits the amount of large-scale changes required to a system
18 What is an OO program? What does an OO program consist of? A series of objects that use each others behaviours in order to carry out some desired functionalityWhen one object invokes some behaviour of another it sends it a messageIn Java terms it invokes a method of the other objectA method is the implementation of a given behaviour.OO programs are intrinsically modularObjects are only related by their public behaviour (methods)Therefore objects can be swapped in and out as required (e.g. for a more efficient version)This is another advantage of OO systemsOO programs are highly modular, which can make them very easy to customise and extend. For example I could switch in an entirely different object into the application so long as it has the same behaviour (public interface) as the previous object. The rest of the system is oblivious to the change.That’s why the public interface of an class/object is referred to as its “contract”. Just like a legal document, it canbe seen as an agreement between an object and the others that use its behaviour, that if they send it a particular message (or in Java terms call its method) then some operation will be carried out. How that operation is achieved is of no interest to the calling object.
19 AggregationAggregation is the ability to create new classes out of existing classesTreating them as building blocks or componentsAggregation allows reuse of existing code“Holy Grail” of software engineeringTwo forms of aggregationWhole-Part relationshipsCar is made of Engine, Chassis, WheelsContainment relationshipsA Shopping Cart contains several ProductsA List contains several ItemsAggregation should be familiar to anyone who has used Visual Basic: forms are made up from other components (controls).In engineering terms its like taking pre-fabricated components (e.g. resistors, transistors, etc) and buildingsomething out of those parts (e.g. a radio). Should be obvious why this is the “holy grail” – could significantlyReduce costs of developing software. While OO doesn’t get us there, its currently the best way we know of building maintainable applications.
20 InheritanceInheritance is the ability to define a new class in terms of an existing classThe existing class is the parent, base or superclassThe new class is the child, derived or subclassThe child class inherits all of the attributes and behaviour of its parent classIt can then add new attributes or behaviourOr even alter the implementation of existing behaviourInheritance is therefore another form of code reuseDefine one type in terms of another type.Both motorbikes and cars are types of vehicles.
21 Polymorphism Means ‘many forms’ Difficult to describe, easier to show, so we’ll look at this one in a later lessonIn brief though, polymorphism allows two different classes to respond to the same message in different waysE.g. both a Plane and a Car could respond to a ‘turnLeft’ message,however the means of responding to that message (turning wheels, or banking wings) is very different for each.Allows objects to be treated as if they’re identical
22 Summary! In OO programming we Benefits of OO programming Define classesCreate objects from themCombine those objects together to create an applicationBenefits of OO programmingEasier to understand (closer to how we view the world)Easier to maintain (localised changes)Modular (classes and objects)Good level of code reuse (aggregation and inheritance)
23 Overview Introducing Java Principles of Object Oriented Programming Key features of the languagePrinciples of Object Oriented ProgrammingWhat is OOP?Why is it important?The Unified Modelling LanguageUML Class Diagrams
24 Unified Modelling Language UML is a diagramming tool for describing and documenting object oriented applicationsProgramming language independentUsed for modelling an application before its engineeredTwelve different diagrams in all, with many complex detailsGenerally though only two of these are used regularlyClass diagramsSequence diagramsThe reason I’m introducing a few UML basics is because it makes talking about applications much easier, as we can produce a diagram describing the classes and their relationships, rather than just jumping into the code.It’s also a useful skill in its own right, and is generally encountered in OO design documents.
25 Unified Modelling Language Class DiagramsDescribe classes and interfaces…their properties…their public interface…and their relationships (e.g. inheritance, aggregation)Sequence DiagramsDescribe how objects send messages to one anotherUseful for describing how a particular part of an application worksWe’ll be covering just class diagramsVery useful for describing APIs and discussing OO applications
26 UML -- Classes Box with 3 sections The top contains the class name The middle lists the classes attributesThe bottom lists the classes methodsCan indicate parameters and return types to methods, as well as their visibility
27 UML -- Association A line between two classes indicates a relationship Extra information can be added to describe the relationshipIncludingIts nameThe roles that the classes playThe cardinality of the relationship (how many objects are involved)E.g. a Person worksFor a Company, which has many employees
28 UML -- Comments Useful for adding text for the readers of your diagram The symbol looks like a little post-it note, with a dotted line joining it to the class or relationship that its describing
29 UML -- AggregationAggregation (a whole-part relationship) is shown by a line with clear diamond.As aggregation is a form of relationship you can also add the usual extra informationI.e.NameRolesCardinality
30 UML -- InheritanceInheritance is shown by a solid arrow from the sub-class to the super-classThe sub-class doesn’t list its super-class attributes or methods,unless its providing its own alternate version (I.e. is extending the behaviour of the base class)
31 UML -- InterfacesInterfaces are a way to specify behaviour (a public contract) without data or implementation.Interfaces are classed with an extra label next to their name: <<Interface>>A dotted arrow from a class to an interface explains that the class fulfills the contract specified by that interface