1 Java Java Object oriented features Object oriented features Polymorphic type Polymorphic type Inheritance Inheritance Information Hiding Information Hiding Modules Modules Interface vs. Implementation Interface vs. Implementation Separate Compilation Separate Compilation Security Security Software Engineering Software Engineering Maintenance – No global variables, type checks Maintenance – No global variables, type checks High level functionality – Well defined Framework High level functionality – Well defined Framework Documentation – Automatic Documentation – Automatic Organization/Modules -- Organization/Modules -- Interfaces, contracts, and implementation Interfaces, contracts, and implementation
25
Embed
1 Java Object oriented features Object oriented features Polymorphic type Polymorphic type Inheritance Inheritance Information Hiding Information Hiding.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
11
JavaJava
Object oriented featuresObject oriented features Polymorphic typePolymorphic type InheritanceInheritance Information HidingInformation Hiding
ModulesModules Interface vs. ImplementationInterface vs. Implementation Separate CompilationSeparate Compilation SecuritySecurity
Software EngineeringSoftware Engineering Maintenance – No global variables, type checksMaintenance – No global variables, type checks High level functionality – Well defined FrameworkHigh level functionality – Well defined Framework Documentation – Automatic Documentation – Automatic Organization/Modules -- Organization/Modules -- Interfaces, contracts, and implementationInterfaces, contracts, and implementation
22
The Java Programming The Java Programming LanguageLanguage
33
Why Java?Why Java? Originally developed at Sun for embedded Originally developed at Sun for embedded
consumer devices.consumer devices. Cable TV set-top boxes, etc.Cable TV set-top boxes, etc. Developed by James GoslingDeveloped by James Gosling
Code distributed to devices via a wide area Code distributed to devices via a wide area network.network. Many different kinds of devicesMany different kinds of devices SecuritySecurity ReliabilityReliability
Popularity of WWW in early 1990sPopularity of WWW in early 1990s Sun retargets Oak as a general programming languageSun retargets Oak as a general programming language Renamed to JavaRenamed to Java Applets for the Web pages Applets for the Web pages
44
How is Java different from other languagesHow is Java different from other languages
Less than you think:Less than you think: Java is an Java is an imperativeimperative language (like C++, Ada, C, language (like C++, Ada, C,
Pascal)Pascal) Java is Java is interpreted byte codeinterpreted byte code (like LISP, APL) (like LISP, APL) Java is Java is garbage-collectedgarbage-collected (like LISP, Eiffel, Modula-3) (like LISP, Eiffel, Modula-3) Java can be Java can be compiledcompiled (like LISP) (like LISP) Java is Java is object-orientedobject-oriented (like C++, Ada, Eiffel) (like C++, Ada, Eiffel)
But introduces important new featuresBut introduces important new features Java includes Java includes documentationdocumentation standards in language standards in language Java includes Java includes securitysecurity features features Java includes Java includes reflectionreflection to reveal meta-information to reveal meta-information
A successful hybrid for a specific-application A successful hybrid for a specific-application domaindomain
A reasonable general-purpose language for A reasonable general-purpose language for non-non-real-timereal-time applications applications
55
Original design goals (white paper 1993)Original design goals (white paper 1993)
SimpleSimple (easy to learn and use)(easy to learn and use) Object-orientedObject-oriented (inheritance, polymorphism)(inheritance, polymorphism) DistributedDistributed (intended for networks)(intended for networks) InterpretedInterpreted (by Java Virtual Machine, JVM)(by Java Virtual Machine, JVM) MultithreadedMultithreaded (built-in synchronization (built-in synchronization
primitive)primitive) RobustRobust (strongly typed)(strongly typed) SecureSecure (run-time security checks)(run-time security checks) Architecture-neutral Architecture-neutral (JVM for many platforms)(JVM for many platforms)
A language with threads, objects, exceptions A language with threads, objects, exceptions and garbage-collection can’t really be simple!and garbage-collection can’t really be simple!
66
PortabilityPortability
Critical concern: Critical concern: write once-run everywherewrite once-run everywhere Intended for distribution over wide area networkIntended for distribution over wide area network Consequences:Consequences:
Portable interpreterPortable interpreter definition through virtual machine: the definition through virtual machine: the JVMJVM run-time representation has high-level semanticsrun-time representation has high-level semantics supports dynamic loadingsupports dynamic loading (+) high-level representation can be queried at run-time (+) high-level representation can be queried at run-time
to provide reflectionto provide reflection (-) Dynamic features make it hard to fully compile, (-) Dynamic features make it hard to fully compile,
Contrast with conventional systems Contrast with conventional systems languageslanguages
(C, C++, Ada)(C, C++, Ada)
Most Conventional languages are fully compiled:Most Conventional languages are fully compiled: run-time structure is run-time structure is machine languagemachine language (not portable) (not portable) minimal or minimal or nono run-time type informationrun-time type information language provides low-level tools for accessing storagelanguage provides low-level tools for accessing storage safety requires fewer run-time checks because compilersafety requires fewer run-time checks because compiler
(least for Ada and somewhat for C++) can (least for Ada and somewhat for C++) can verify verify correctness statically.correctness statically.
Languages require static binding, run-time image cannot Languages require static binding, run-time image cannot be easily modifiedbe easily modified
Different compilers may create Different compilers may create portability problemsportability problems
88
Language ChangesLanguage Changes Improvements since Java was introduced in Improvements since Java was introduced in
19951995 Event ModelEvent Model Nested ClassesNested Classes Parameterized classesParameterized classes (C++ templates, Ada (C++ templates, Ada
generics) in Java 1.5 (Beta)generics) in Java 1.5 (Beta) Many Java Technologies (JavaBeans, Telephony, …)Many Java Technologies (JavaBeans, Telephony, …) (Distinction between libraries and language is (Distinction between libraries and language is
diminishing) diminishing) But Java Still has omissions:But Java Still has omissions:
No No operator overloadingoperator overloading (syntactic annoyance) (syntactic annoyance) No No enumeration typesenumeration types (using final constants is (using final constants is
clumsy)clumsy)
99
JavaDocJavaDoc Automatically generates user documentationAutomatically generates user documentation
Special comments containing keywordsSpecial comments containing keywords /** /** this introduces a special comment this introduces a special comment ** ** @author@author Guy Steele Guy Steele **/**/
KeywordsKeywords @return@return – return value– return value @param@param – parameter– parameter @throws@throws – describes an exception that method throws– describes an exception that method throws
Comment associated with class or method immediately Comment associated with class or method immediately following the commentfollowing the comment
Can include HTML tagsCan include HTML tags Makes it easier to document codeMakes it easier to document code Helps keep documentation currentHelps keep documentation current Extensible: record rationale, maintenance Extensible: record rationale, maintenance
instructions, etc.instructions, etc.
1010
InterfacesInterfaces Separate Separate specificationspecification from from implementationimplementation Allow related classes to satisfy a given Allow related classes to satisfy a given
requirementrequirement Orthogonal to inheritanceOrthogonal to inheritance
inheritanceinheritance: an A : an A is-ais-a B (has the attributes B (has the attributes of a B, and possibly others)of a B, and possibly others)
interfaceinterface: an A : an A can-docan-do X (and other X (and other unrelated actions)unrelated actions)
better model for multiple inheritancebetter model for multiple inheritance More costly at run-time (minor More costly at run-time (minor
consideration)consideration)
1111
Interface ComparableInterface Comparable
public interfacepublic interface Comparable { Comparable {public intpublic int CompareTo (Object x) CompareTo (Object x) throwsthrows
ClassCastException;ClassCastException;// returns -1 if this < x,// returns -1 if this < x,// 0 if this = x, // 0 if this = x, // 1 if this > x// 1 if this > x
};}; Implementation has to Implementation has to castcast x to the proper class. x to the proper class. Any class that may appear in a container should Any class that may appear in a container should
implement Comparableimplement Comparable
1212
Interfaces and event-driven programmingInterfaces and event-driven programming
A high-level model of event-handling:A high-level model of event-handling: graphic objects generate graphic objects generate eventsevents
mouse click, menu selection, window close...mouse click, menu selection, window close... an object can be designated as a an object can be designated as a handlerhandler
a a listenerlistener, in Java terminology, in Java terminology an event can be broadcast to several handlersan event can be broadcast to several handlers
several listeners can be attached to a source of several listeners can be attached to a source of eventsevents
a handler must a handler must implement an interfaceimplement an interface actionPerformed, keyPressed, mouseExitedactionPerformed, keyPressed, mouseExited....
1313
Events and listenersEvents and listeners
classclass Calm_Down Calm_Down extendsextends Jframe { Jframe { private Jbutton help := private Jbutton help := newnew Jbutton (“HELP!!!”); Jbutton (“HELP!!!”); // indicate that the current frame handles button clicks// indicate that the current frame handles button clicks help.addActionListener (help.addActionListener (thisthis););
// if the button is clicked the frame executes the following:// if the button is clicked the frame executes the following: public voidpublic void actionPerformed (ActionEvent e) { actionPerformed (ActionEvent e) { if if (e.getSource () == help) {(e.getSource () == help) { System.out.println(“can’t be that bad. What’s the System.out.println(“can’t be that bad. What’s the
problem?”);problem?”); }} }} }}
1414
Introspection, Reflection, and Introspection, Reflection, and Typeless programmingTypeless programming
// we know the methods in class Gizmo// we know the methods in class Gizmo
… ….. InstanceofInstanceof requires an accessible run-time descriptor in requires an accessible run-time descriptor in
the object.the object. Reflection is a general programming model that relies on Reflection is a general programming model that relies on
run-time representations of aspects of the computation that run-time representations of aspects of the computation that are usually are usually not available to the programmernot available to the programmer..
More common in Smalltalk and LISP.More common in Smalltalk and LISP.
1515
Separate CompilationSeparate Compilation Compilers need to know type of objects Compilers need to know type of objects
defined elsewhere at compile timedefined elsewhere at compile time Ada separates Ada separates specspec and and bodybody C and C++ use C and C++ use header filesheader files Java constructs Java constructs class files class files which contain:which contain:
Method descriptions, including method Method descriptions, including method signatures signatures and and Byte codeByte code
A A constant poolconstant pool with names and constant values with names and constant values Reflection Reflection information information
Package structure related to Package structure related to Network implementationNetwork implementation File systemFile system
1616
Reflection and Reflection and MetaprogrammingMetaprogramming
Given an object at run-time, it is possible to obtain:Given an object at run-time, it is possible to obtain: its its classclass its its field namesfield names (data members) as strings (data members) as strings the the classesclasses (types) of its fields (types) of its fields the the method namesmethod names of its class, as strings of its class, as strings the the typestypes of the methods of the methods
It is then possible to construct calls to these It is then possible to construct calls to these methodsmethods
This is possible because the JVM class file provides a This is possible because the JVM class file provides a high-level representation of a class, with embedded high-level representation of a class, with embedded strings that allow almost complete disassembly.strings that allow almost complete disassembly.
Protected by Java’s security systemProtected by Java’s security system
Class.forName(className) Class.forName(className) // creates a Class object// creates a Class object
Class.getMethods () Class.getMethods () // returns array of method objects// returns array of method objects
Class.getConstructor (Class[] parameterTypes)Class.getConstructor (Class[] parameterTypes)//returns the constructor with those parameters//returns the constructor with those parameters
Class.isInterface() Class.isInterface() // true if the “class” is an interface// true if the “class” is an interface
Reflection Classes Reflection Classes Allows access to objects at run-timeAllows access to objects at run-time
Java BeansJava Beans High level componentsHigh level components Communicate with eventsCommunicate with events
1818
Reflection and beansReflection and beans The beans technology requires run-time The beans technology requires run-time
examination of foreign objects, in order to examination of foreign objects, in order to build dynamically a usable interface for them.build dynamically a usable interface for them.
Class Introspector builds a method dictionary Class Introspector builds a method dictionary based on simple naming conventions:based on simple naming conventions:
public booleanpublic boolean isCoffeeBean ( ); isCoffeeBean ( ); // is... predicate// is... predicate public int public int getRoast ( ); getRoast ( ); // get... retrieval// get... retrieval public voidpublic void setRoast ( setRoast (int int darkness) ; darkness) ; // set… assignment// set… assignment
getBeanInfo(Class.fromName(“CoffeeBean”));getBeanInfo(Class.fromName(“CoffeeBean”)); Returns a BeanInfo objectReturns a BeanInfo object
1919
SecuritySecurity Essential for distributing code over the internetEssential for distributing code over the internet
Untrusted code ran in “Sandbox” on original JavaUntrusted code ran in “Sandbox” on original Java Now Java has fine-grained security system Now Java has fine-grained security system
Restricts access to system resourcesRestricts access to system resources reading or writing files, system exit, etc.reading or writing files, system exit, etc.
Based on a Based on a PolicyPolicy that grants that grants permissionspermissions Code base (e.g. a URL)Code base (e.g. a URL) Signer (names a set of public keys) Signer (names a set of public keys) Permissions (e.g. reading files) Permissions (e.g. reading files)
ClassLoader controls which classes have which ClassLoader controls which classes have which permissionspermissions
2020
Declarative Declarative ProgrammingProgramming
2121
PrologProlog
Logic ProgrammingLogic Programming Theorem ProvingTheorem Proving Program is a series of statements Program is a series of statements
(axioms) and a goal(axioms) and a goal Execution attempts to prove goalExecution attempts to prove goal
Reach goal from axiomsReach goal from axioms Uses inference Uses inference
2222
Horn ClausesHorn Clauses A Horn clause is of the formA Horn clause is of the form
C C B B11, B, B22, B, B33, …, B, …, Bn-1n-1, B, Bnn
C C is the is the Head Head or or ConsequentConsequent BBii is an term of the is an term of the BodyBody When When BBii is true for all is true for all ii = 0..n. then = 0..n. then CC is true is true
If If C C A, B A, B and and D D C C thenthen D D A, B A, B Terms are usually parameterized predicatesTerms are usually parameterized predicates
Rainy(Seattle) Rainy(Seattle) True iff it rains in SeattleTrue iff it rains in Seattle
UnificationUnification Process of substituting Process of substituting expressionsexpressions for for
variablesvariables A A constantconstant unifies only with itself unifies only with itself Two Two structuresstructures unify iff predicate is the unify iff predicate is the
same, the number of parameters is the same, the number of parameters is the same and corresponding parameters same and corresponding parameters unify (recursively)unify (recursively)
Variables unify with:Variables unify with: Values – variable instantiated with valueValues – variable instantiated with value Other Variables – names alias each otherOther Variables – names alias each other
Unification also used in ML type inferenceUnification also used in ML type inference
2424
A Prolog ProgramA Prolog Program A Program is a sequence of A Program is a sequence of
A Query is applied to the programA Query is applied to the program ?- snowy(C)?- snowy(C) C = rochesterC = rochester
Interpreter may return only the first or Interpreter may return only the first or all values satisfying the queryall values satisfying the query
2525
ApplicationsApplications LimitationsLimitations
Unification can take exponential timeUnification can take exponential time Subset of first order logicSubset of first order logic
notnot is inability to prove, not false is inability to prove, not false Can be used forCan be used for
Problems for which efficient and Problems for which efficient and straightforward procedural solutions are not straightforward procedural solutions are not availableavailable
Natural LanguageNatural Language AI and Expert SystemsAI and Expert Systems Relationships (student of, ancestor of)Relationships (student of, ancestor of) Relational Database-like applicationsRelational Database-like applications