G52PGP Lecture oo3 Java (A real object oriented language) 1
Last lecture Associating functions with data into objects is an alternative way to decompose a program Can then consider each object on its own Adding member functions to a class (or struct) Act on a specific object Get an implicit object pointer called thisas a parameter (equivalent) Means that they can access private data Static member functions Do not get the implicit thispointer Can still access private data (if you provide the pointer) 2
Java This lecture There is no C or C++ in the exam or coursework There is some Java in both I covered C (and some C++) only to link Java to what you have done so far Hopefully this helps you to understand what these things in Java are really doing Some standard Java classes System: Class for things like text output JFrame: top level windows JLabel: GUI component labels within a window 3
Java s Genealogy
Java s Genealogy : C -> C++ ->Java It is not just a coincidence that Java is so similar to C And we can emulate the Java facilities in C Java was designed to be easy for C++ programmers to learn
Simple Text Hello World public class HelloWorld { public static void main(string[] args) { System.out.println( "Hello World!" ); } } What do you think the main() function does? Why is the main function static? What do you think the public modifier does? What do you think System.out.println() does? 6
Simple Text Hello World public class HelloWorld { public static void main(string[] args) { System.out.println( "Hello World!" ); } } Filename must match the class name E.g. HelloWorld.java i.e. only one top-level class per file Exception for inner classes (classes in classes see later) 7
Getting started with Eclipse Either download and install the JDK from the link below, making sure to get the correct version for your system: http://www.oracle.com/technetwork/java/javase/downl oads/index.html Or download the latest version of Eclipse IDE for Java Developers from the Eclipse homepage using the link below: http://www.eclipse.org/downloads/ Then Unzip Eclipse somewhere sensible Then just run eclipse Or use any other Java IDE you wish to use
Example: Create, build and execute Eclipse Create program Compile program Execute program Manually working with Java programs Manually compile program Manually execute program.class files Packages, package structure 9
JDK basic tools javac(compiler).java->.class The Java Language Compiler that you use to compile programs written in Java into bytecodes. Example : javac HelloWorld.java java (Interpreter) executes.class The Interpreter that you use to run programs written in Java. Example : java HelloWorld javadoc(doc. generator).java html Generates documentation in HTML format from Java source code. Example : javadoc HelloWorld.java
Eclipse Create a new project Do this for each coursework File > New > Java Project Use a meaningful name eg G51PGPCW1
Create a new class Create a new class Right click project name Choose Add Choose Java Class You could put it into a package (I didn t) Choose to create the main() function 13
Useful parts of the IDE Package explorer Java files Debug Run Source file Type your code in here Output will appear in here As will compilation results
Debugging views, at a breakpoint Right click in the left margin to set a breakpoint Resume Step into, step over Current code line Call stack Current variable values 15
Java key features (vs C/C++) Simplifies a lot of the things that cause bugs in C++ No pointers? uses object references instead These act like pointers but you can t use the address they hold Unfortunately pointer arithmetic sometimes used for speed in C++ No need to free memory runtime will deal with it Garbage collection is a common cause of program stall Platform independent Creates intermediate byte code rather than platform specific Executed through a virtual machine rather than native executable Some native compilers exist Just-in-time compilation is usually used to allow for optimisations Many tests indicate it s almost as fast as C/C++ Platform independent libraries for most things 16
Java vs C/C++ differences Tries to promote true object oriented programming Removed global functions (can use static members though) Library functions often take or return temporary objects Speed and efficiency is not the primary concern No malloc() The new operator is used instead C++ also uses new and delete, so not unusual It frees memory automatically wonderful feature (if annoyingly slow) No local variable objects Objects only on heap, not the stack Object references (i.e. pointers to objects) can be local variables though No access directly to memory locations Issues for device drivers or CUDA, no optimisation of data layout/caching Some syntactic differences between C++ and Java No use of * to dereference pointers Uses. rather than -> (has no objects on stack, so no other use for.) No ; at the end of class definitions 17
Some Java conventions Use capital first letter for class names E.g. String, Array, Book, Plane, Car, etc Use lower case first letter for variable name and method name E.g. i, counter, computer, input, etc When names have multiple words, capitalise the first letter of subsequent words E.g. mycomputer, largearray, etc Or class names: BookArray, SetOfCars, Braces: Original style guide says to add open brace to end of line, and put closing brace on a new line I usually (except for space reasons on slides) put the open brace on a new line, to aid in debugging (matching the braces) Whichever you do, please be consistent (even if I am not ) 18
Data Basic data types int, float, boolean, double, long, char, etc Objects Object references act like C/C++ struct pointers Need to use new(or a function which does so) to create the object If you didn t use new(or call a function which does so), you don t have an object Assigning one reference to another means make it refer to (point at) the same object Pass an object reference into a function, or return one, means referring to the same object, NOT creating a new one String Hybrid of objects and basic types No need to use new Passed around like objects by reference rather than making copies Support overloaded + operator, to concatenate Stringsto make a new String Think of these as a different or hybrid type of thing Look up the StringBufferobject if you want a bit more speed 19
Example of basic GUI Hello World import java.awt.flowlayout; import java.awt.font; import javax.swing.jframe; import javax.swing.jlabel; public class GUIHelloWorld {// Just the one class public static void main(string[] args) {// Same main function as before static JFrameguiFrame= new JFrame(); // Create a new frame object top level window guiframe.setdefaultcloseoperation(jframe.exit_on_close); // Close window exits guiframe.settitle("hello World!"); // Set a caption/title bar content for the frame guiframe.setlocationrelativeto(null); // centre on screen guiframe.setlayout( new FlowLayout() );// Layout : how to layout components JLabellabel= new JLabel(); // Create a new label object label.settext("hello World (again)!");// Set its message to show label.setfont(new Font("Ariel", Font.BOLD, 30));// Set a font for the label guiframe.add(label); // Add the label to the frame, so that it will show guiframe.pack(); // Resize frame to fit content guiframe.setvisible(true); // Display it until you do it will not appear } } 20
Next lecture We have seen some objects Grouping of data and some functions to act upon it We have seen some basic Java code There is a coursework/lab exercise to do, which will allow you to practise this Next lecture we will look at some more Java code, what we are really doing, and then at how to identify appropriateobjects in our own programs, and the basics of object oriented design 21