2.54k likes | 2.56k Views
Java Fundamentals. by Chris Seddon. Java Fundamentals. 1 Introduction to Java 2 Classes 3 Packages 4 More on Classes 5 Strings and Arrays 6 Aggregation and Association 7 Inheritance 8 Exception Handling 9 Abstract Classes and Interfaces 10 Collections
E N D
Java Fundamentals byChris Seddon
Java Fundamentals • 1 Introduction to Java • 2 Classes • 3 Packages • 4 More on Classes • 5 Strings and Arrays • 6 Aggregation and Association • 7 Inheritance • 8 Exception Handling • 9 Abstract Classes and Interfaces • 10 Collections • 11 Reflection and Classloaders • 12 Multithreading • 13 Advanced Threading • 14 Concurrency • 15 New Features in Java 5 • 16 Generics
What is Java? • Java • is a fully object oriented language • was designed by Sun in early 1990s • based on C/C++ • unsafe features of C/C++ removed • no pointers • no pre-processor • no automatic garbage collection • advanced features of C++ omitted • no templates • no operator overloading • no customising memory allocators • Sun’s White Paper says: • Java is a simple, object-oriented, distributed, interpreted, robust, secure, architecture neutral, portable, high-performance, multi-threaded and dynamic language.
Java Design Criteria • Platform-independence • Java code is compiled into processor-independent bytecodes • bytecodes are interpreted by the Java Virtual Machine • same program runs on any platform that supports Java • Robust • fully object oriented: everything belongs to a class • type checking • exception handling • Small and efficient • classes only loaded if required • built-in multi-threading support • Secure • runtime environment enforces security
Running a Java Program • Java Virtual Machine (JVM) • stand-alone program • controls all Java programs • many different JVMs available • use plugin to add to browsers • such as Firefox and Internet Explorer Compiler JVM running program YourClass.java YourClass.class
Java Application/Applet Java Virtual Machine (JVM) Browser or other Container Operating System (Unix, Windows NT) The Java Virtual Machine (JVM) • Class loader • searches for Java classes • loads and runs classes inside the JVM • Verifier • checks class for illegal code • helps prevent viruses and malicious code • Security restrictions • limits file and network access • Garbage collection • Garbage-collector thread cleans up all dead objects
Java Applications • Standalone applications • written in Java • program runs under control of the JVM • use RMI to access network • Must have a public class defined • with a main method (entry point) C:\student> javac HelloWorld.java ... compiler output ... C:\student> java HelloWorld public class HelloWorld { public static void main(String[ ] args) { System.out.println("Hello World"); } }
Java Applets • Client side Applets • run inside a browser • browser houses the JVM • applets embedded within a page of HTML <HTML> <HEAD> <TITLE>Hello World</TITLE> </HEAD> <BODY> This is the applet <APPLET CODE="HelloWorld.class" CODEBASE="C:\Student" WIDTH=400 HEIGHT=200> </APPLET> </BODY> </HTML>
Java Packages • Each package contains • classes • interfaces java.applet java.awt java.awt.event java.io java.lang java.math java.rmi java.security java.sql java.util javax.swing classes for creating applets classes for creating user interfaces and for painting graphics provides classes and interfaces for dealing with events system input and output fundamental classes classes for performing integer and decimal math functions classes for RMI provides the classes and interfaces for the security framework classes for JDBC collections classes, date and time facilities, ... set of "lightweight" graphical components
Java Security • The Original Sandbox Model • provides a very restricted environment in which to run untrusted code obtained from the internet • Security Manager • allows permission based and configurable access control to local resources such as files • when code is loaded, it is assigned "permissions" based on the security policy file • e.g. "read" and "write" access to a specified file or directory • or "connect" access to a given URL • Digital Certificates • full support for managing digital certificates • uses Secure Socket Layer (SSL) • which in turn uses Public Key Encryption (PKI)
Java Versions and Tools • Java Versions • Java 1 (JDK 1.0, 1.1) • Java 2 (JDK 1.2, 1.3, 1.4, 5.0, 6.0) • Java 2 Enterprise Edition (J2EE) • JDBC, JNDI, RMI, Java IDL, Servlets, JSP, EJB, JTS, JTA, Java Mail, JAF, JMS, XML ... • Servlets, JSP, JSF, EJB • Development Tools (include ...) • javac Java compiler • java Java virtual machine • appletviewer Stand alone applet viewer tool • jdb Command line debugger • jar Java archive generator • keytool Certificate management • jarsigner Digital signing of jar files
Java 2 Enterprise Edition (J2EE) Web Server Web Client Data server Servlets JSPs HTTP JDBC RMI EJBs Application Client RMI
Naming Service (JNDI) Remote JVM Local JVM client server stub skeleton marshaling RMI (Remote Method Invocation) • Allows client to invoke methods on different JVM • JVM may be on same machine • JVM may be on local network • JVM may be somewhere on the internet • JNDI (Java Naming Directory Interface) • used by client to look up server objects
Web Servers • WebSphere (IBM) • top ranked commercial Application Server • complex configuration • Weblogic (Oracle) • very powerful and popular commercial Application Server • simple configuration • JBoss Application Server • best Open Source solution • built on top of Tomcat • Tomcat • reference server for Servlets/JSP • often used as a production server
Development Environments • Development environments include ... • Eclipse • NetBeans (Sun) • JBuilder (Borland) • Debugging • full local and remote debugging as standard • Eclipse • not just Java • C/C++/Perl/Jython and many more • can be core component of user applications • using plug-in technology • has its own graphical library
Classes • 2
Classes and Objects • Classes • what is a class • what is an object • Object methods • public and private • call by value • call by reference • Object instance variables • public and private • Constructors and finalizers
The Object Model • Object-oriented programming • modelling real-world objects • model described by classes • model implemented by creating objects
Classes • A class defines • a new data type • its operations • its state Type Yacht { Tack Operations DropAnchor } length State draft
Classes class Yacht { public void Tack() { // implementation } public void DropAnchor() { // implementation } private int length; private int draft; } Operations State
Objects • A class is a blueprint for building objects • An object is an instance of a class Yacht public void Tack() public void DropAnchor() private int length; private int draft; Object 1 Object 2 length = 40 draft = 1.7 length = 30 draft = 1.3
Creating Objects • Use the new operator • returns an object reference void CreateYachts() { Yacht oceanis; oceanis = new Yacht(35, 1.6); Yacht mirror = new Yacht(25, 1.2); } • Note: • just declaring an object reference does not create an object Yacht y; // y is a reference, not an object
How does new work? • new • allocates memory for the object on the HEAP • initialises the object by calling a constructor • returns a reference • to the new object on the STACK mirror length = 25 draft = 1.2 Yacht mirror = new Yacht(25, 1.2);
The null Reference • Object references initialised as null • Objects are reference counted • Release an object by setting reference to null Yacht oceanis; if (oceanis == null) { System.out.println("Not initialised"); oceanis = new Yacht(); } oceanis = null; // release object
Assigning References • Assigning references • both point to the same object mirror1 length = 25 draft = 1.2 mirror2 Yacht mirror1 = new Yacht(25, 1.2); Yacht mirror2; mirror2 = mirror1;
Object references stored on STACK point to objects only the reference copied Copying Primitives and Objects • Primitive variable • stored on STACK • holds a value • variable copied class Boat { private int value; private Yacht yacht; void ChangeValue(int newValue) { value = newValue; } void ChangeBoat(Yacht newYacht) { yacht = newYacht; } }
Client Code TestBoat.java public class TestBoat { static void main(String[ ] args) { Yacht oceanis = new Yacht(30, 1.6); Boat myBoat = new Boat(); myBoat.ChangeValue(25000); myBoat.ChangeBoat(oceanis); } } Boat.java class Boat { private int value; private Yacht yacht; void ChangeValue(int newValue) { value = newValue; } void ChangeBoat(Yacht newYacht) { yacht = newYacht; } }
Defining Constructors • constructors initialise objects • no return type (not even void) • different signature class Yacht { private int length; private int draft; public Yacht() { length = 25; draft = 1.2; } public Yacht(int theLength, double theDraft) { length = theLength; draft = theDraft; } public void Tack() { ... } public void DropAnchor() { ...} } class TestYacht { static void main(String[ ] args) { Yacht mine, yours; mine = new Yacht(33, 1.5); yours = new Yacht(); } }
Defining Finalizers • finalizers tidy up objects • called when garbage collector runs • can't be sure when • might never get called! class Yacht { private int length; private int draft; public Yacht() { ...} public Yacht(int l, int d) { ... } public void Tack() { ... } public void DropAnchor() { ...} public void finalize() { // code to clean up object } } class TestYacht { static void main(String[ ] args) { Yacht mine, yours; mine = new Yacht(33, 1.5); yours = new Yacht; } }
Encapsulation • methods and state (instance variables) • may be hidden • using modifiers • keep state private! modifier recommended usage public protected default private for methods for subclassing methods for methods in a package for helper methods and state
Packages • 3
Java Packages • Packages • Class files and Source Files • Directory Structure • Compilation • Classpath • Jar Files
Compiling Source to Bytecode • Source code • only 1 public class • file name same as public class name • case SeNSitivE Person.java Person.class public class Person { . . . } class Car { . . . } 011000100101101011101000101010011011010101101010101110110011000000100101 compile Car.class 01110100010101001101101000101101010100110101011010100011110100101011101010010010100100101
Packages • Packages • reduce name conflicts • define directory structure (utilise DNS names) • A class can access other classes in package • all source file in a package are in the same directory uk Person.java compile package uk.co.ssl; public class Person { . . . } co ssl Person.class
Compilation • Compile relative to the root directory • Include the package name in compilation command • Output files can be placed in a new directory tree cd c:\JavaFiles javac -d c:\MyClasses uk\co\ssl\Person.java c:\JavaFiles c:\MyClasses uk uk co co ssl ssl Person.java Person.class
Running Java Programs (1) • Run relative to the root directory • Include the package name in the run command cd c:\JavaFiles javac -d c:\MyClasses uk\co\ssl\Person.java cd c:\MyClasses java uk.co.ssl.Person c:\MyClasses uk co ssl Person.class
Running Java Programs (2) • Running the Java class from a different directory • not practical to always run relative to the root directory • how does the JVM locate the Person class? cd c:\JavaFiles javac -d c:\MyClasses uk\co\ssl\Person.java cd c:\SomewhereElse java uk.co.ssl.Person c:\MyClasses uk co ssl Person.class
Classpath • .java file location = Class Path + Package Path @echo off set DRIVE=c: set WL_HOME=%DRIVE%\WebLogic set STUDENT=%DRIVE%\Student set WlClasses=%WL_HOME%\classes set WLAux=%WL_HOME%\lib\weblogicaux.jar set CLASSPATH=.;%STUDENT%;%WlClasses%;%WlAux% java -classpath %CLASSPATH% MyClass.class
The classpath Variable To execute the program c:\java_stuff\uk\co\ssl\Examples\Mylib\Cars.class If the package name is: uk.co.ssl.Examples.Mylib and the class is: public class Cars { ... } then the classpath must contain: CLASSPATH= ...;c:\java_stuff; ...
Jar Files • Jar Files • Java archive packages classes • convenient way to store many java class files • similar to Unix tar command jar {ctxu} [vfm] [outfile] [manifest] infiles... ctxu create, tabulate, extract, update v verbose f output jarfile specified m manifest specified outfile output jarfile manifest manifest specified infiles list of input files or directories (can use wildcards)
Example Jar Commands • Jar Command • specify output file • use directory as input • use files as input • use wildcards in input specification jar -cf uk\co\ssl\Examples\myJar.jar uk\co\ssl\Examples\*.class jar -uf myJar.jar META-INF\ cd c:\weblogic\server50\Sorting jar -cvf Sorting.war *
More on Classes • 4
More on Classes • Method Overloading • Passing Parameters • Static Class Variables • Static Methods • Constants and Final