Workshop for Programming And Systems Management Teachers Chapter 9 Source File Anatomy Georgia Institute of Technology Learning Goals • Understand at a conceptual and practical level the anatomy of a Java source file – – – – Optional Comments Optional Package Declaration Import Statements as needed Class Declarations • Attributes • Constructors • Methods – Applet Anatomy Georgia Institute of Technology Structure of a Java Source File Comments (like copyright) Package statement Import statements Class definition { Attributes Constructors Methods Main method (if application) } Georgia Institute of Technology Comments • There are three types of comments in Java – A multi-line comment /* here is a multi-line comment it ends here */ – A single line comment // comments out the rest of this line – A javadoc comment /** Method to return the name of the person */ @author name - adds an author entry @version text - adds a version section @param name description - adds a parameter description @return description - describes the return value of a method Georgia Institute of Technology Comment Exercise • Open SimplePicture.java and read some of the comments – Which are Javadoc comments? – Which are single line comments? – Which are multi-line comments? • Click on the Javadoc button to generate documentation from the Javadoc comments – Compare the html documentation to the original Javadoc comments Georgia Institute of Technology Packages • Packages allow you to organize your classes into a hierarchy. The package hierarchy is also used for the directory structure. – edu.gatech.ice.Class should be in edu/gatech/ice/ • Package names for packages intended for release outside the organization are like the reverse of the internet domain names. – com.sun.java.swing – edu.gatech java.lang • Every class belongs to a package. If none is specified then the unnamed package is used. Georgia Institute of Technology Common Packages • java.lang - Basic classes, including strings and objects • java.util - Utility classes including generic data structures • java.awt - User interface and graphics • javax.swing - Newer user interface classes • java.applet - Support for applets • java.net - Networking support (URLs, TCP, UDP) • java.io - Input and output to files and streams Georgia Institute of Technology Package Statement • The package statement has to be the first line of code in a source file, if it is specified. It can follow a comment. – package packageName; for example /** Copyright notice */ package edu.gatech.ice; Georgia Institute of Technology Import Statements • If you wish to use classes from a different package than the declared package you can import the class using • import java.awt.Color; or • import java.awt.*; // import just Color // all classes in java.awt – doesn’t include the file like in C so there is no penalty to using the wildcard – doesn’t extend to children of that level. For example importing java.awt.* doesn’t import java.awt.event.*; • Or you can use the full name – java.awt.Color Georgia Institute of Technology How do you know what to import? • If you use a class that is part of Java and you get a compiler error – Error: Undefined class • Use the all classes list of the API to find the class and check the documentation for the package it is in Georgia Institute of Technology Import Exercise • Change SimplePicture.java to specify all the classes that are being imported – Rather than using • import java.awt.*; • Import java.io.*; • Comment out the import statements with a wildcard ‘*” – select lines-> Edit-> Comment Line(s) • Compile and see what classes it says are undefined • Find the classes in the API and add a fully qualified import statement for each – import java.awt.Color; Georgia Institute of Technology Class Definition [Class modifiers] class ClassName [extends ClassName] [implements Interface1,…] { attributes, constructors, methods } • Visibility Class Modifiers – no modifier means the class is visible to all classes in the same package – public - visible to any class. A file can have only one public class. – private - visible only to classes in the same file Georgia Institute of Technology Class Definition Examples public class Person implements Comparable { attributes, methods, and inner classes } private class Helper extends Object { attributes, methods, and inner classes } Georgia Institute of Technology Optional Extends Clause • The “extends Class” clause tells you which class is the parent class – The one the current class inherits from – The parent, super, or base class • If there is no “extends Class” clause – The class inherits from Object • In the package java.lang Georgia Institute of Technology Inheritance Exercise • What is the parent class of each of these classes? – – – – Picture.java SimplePicture.java Sound.java Pixel.java • Where is the show method defined that we have been using to show Picture objects? • Where is the play method defined that we used to play Sound objects? Georgia Institute of Technology Optional Implements Clause • The “implements interface1, interface2” lets the class specify the interfaces that the class promises to implement – Any methods defined in the interfaces must be defined in the class • Or the code will not compile • An interface is like a communications contract – How two classes will communicate – Without worrying what about what classes they are • An interface name can be used as a type – For variable declarations Georgia Institute of Technology Comparable Interface • What if you want to compare two objects? – To find out if one is less than another (< 0) – Or equal to the other (= 0) – Or greater than the other (> 0) • How would you compare people? – playing cards? – shoppers? • Each class needs to decide what this means – But we need to know what method to call int compareTo(Object o) Georgia Institute of Technology Interface Exercise • What interface does SimplePicture.java implement? • Find that interface – Defined in a file with the interface Name.java • What methods are declared in the interface? • Find the same methods in SimplePicture.java Georgia Institute of Technology Attributes • Attributes are the data that each object knows about itself. – All object methods in the class have access to the object attributes • Can use just the attribute name • Can also use this.attribute name • Can also use getAttribute() if you follow Java naming conventions – Class and object methods have access to the class attributes • Declared with “static” keyword Georgia Institute of Technology Attribute Exercise • Open SimplePicture.java • What are the attributes (fields)? – Which are object fields? – Which are class fields? • Change the load method to use – setFileName(fileName) instead of • this.fileName = fileName; – Compile – Test by creating a picture and using System.out.println(picture); Georgia Institute of Technology Declaring Attributes • Attributes are declared as [visibility] type name [= value]; Visibility none specified - classes in the same package public - all classes protected - class, subclasses, and other classes in the same package private - only the class itself Type - the type can be one of the following primitive type object type: class, interface, or array Georgia Institute of Technology Visibility Exercise • Open SimplePicture.java – Which fields have public visibility? • Why are these public? – Which fields have private visibility? • Why are these private? Georgia Institute of Technology Constructors • Constructors are called when the new object is created. They initialize the new object. Person currPerson = new Person(“Fred Flintstone”); • Constructors don’t have a return type and have the same name as the class. public Person () // no argument constructor • There can be many constructors but their parameter signatures must be different. public Person() {} public Person(String theName) { name = theName; } } Georgia Institute of Technology Advanced Constructor Information • The compiler will add a no-argument (no parameters) constructor – All fields will have their default values • Objects default to null • Numbers default to zero • Booleans default to false • If you add any constructors – The compiler will no longer add any for you – You will need to write the no-argument constructor • One constructor can invoke another – Use this(parameter List) as first line Georgia Institute of Technology Inheritance and Constructors • If classes have private attributes – Meaning they can’t be directly accessed outside the class – How can you initialize inherited attributes? • Use super(parameters) to call the parent constructor • Must be the first line in a constructor • If not present the compiler will add a super() as the first line in a constructor • Means the parent class must have a no-argument constructor if you aren’t calling super(parameters) in your constructors Georgia Institute of Technology Constructor Exercise • Open SimplePicture.java – How many constructors does it have? – Why do the constructors call super()? • Open Picture.java – How many constructors does it have? • What is different about the constructors? – How would the complier decide which one to use? Georgia Institute of Technology Methods • Methods are the things that object of the class know how to do. • Methods are declared as [visibility] returnType methodName (parameter list) { … [return x;] // if returnType is not void } • Example public String getName() { return name;} Georgia Institute of Technology Method Visibility and Return Type • Visibility – none specified - classes in the same package – public - all classes – protected - class, subclasses, and other classes in the same package – private - only the class itself • Return Type - the return type can be one of the following – primitive type: int, float, double ... – object type: class, interface, or array – void if no value is returned Georgia Institute of Technology Method Parameter List • Can have no parameters – public String getName() • Parameters are listed as type name – public void setName(String name) • Separate parameters with commas – public void multiplyTwo(int x, int y) • You can have several methods with the same name but different parameter signatures. – public void multiplyTwo(float x, float y) – public void multiplyTwo(int x, int y) Georgia Institute of Technology Main Method • Each class can have a main method public static void main(String[] argv) {} • You tell Java which class to start with java ClassName • Execution starts with the main method – There are no objects when you begin so the main method is static (a class method) • In the main method you create object(s) of the class – Then start the simulation Georgia Institute of Technology Add Main Method Exercise • Add a main method to Picture.java to – Create a picture from a specified file – Negate the picture – Show the picture • Execute by Tools->Run Document’s Main Method – Notice that the interactions pane shows java Picture Georgia Institute of Technology Applications Versus Applets • A Java application will have at least one main method – Execution begins at this main – The Java classes are stored on the machine they run on • An applet is a special Java program that runs in a browser – The applet tag is used in an html page – The Java classes are downloaded from a server – The applet runs in the browser window Georgia Institute of Technology Applet Basics • All applets must inherit from java.awt.Applet or javax.swing.JApplet • They don’t have constructors – Use public void init() instead to set-up the applet before it is displayed • Add applet tags to an html document to display the applet in the html page Georgia Institute of Technology How to Embed Applets <html> <head> <title> Message Applet </title> </head> <body> <applet code=“MessageApplet.class" width=200 height=100> </applet> </body> </html> Georgia Institute of Technology Applet Tag <applet code=”x.class" width=200 height=100> <param name=identifier value=“information”> <param name=identifier value=“information”> </applet> • Attributes of the applet tag – code - the name of the .class to start the applet – width - the horizontal size in pixels – height - the vertical size in pixels – codebase - where to find .class files – align - how to align the applet in the page – name - used for applet to applet communication – archive - gives the name of the jar file(s) (1.1+) – hspace - horizontal space around the applet – vspace - vertical space around the applet Georgia Institute of Technology Using Parameters • Use the param tag to specify the parameters in the html file. – <param name=identifier value=“information”> <param name=name value=“Sue”> <param name=numItems value=“3”> • Use getParameter in the applet to read a parameter as a string. – public String getParameter(String paramName) String name = getParameter(“name”); String numString = getParameter(“numItems”); if (numString != null) int numItems = Integer.parseInt(numString); else int numItems = 0; Georgia Institute of Technology Message Applet Exercise • Modify MessageApplet.java to get the string to display as a parameter. • Modify MessageApplet.html to pass in the message as a parameter. Georgia Institute of Technology Steps in Exercise • Edit MessageApplet.java – Add the following line in the init method to get the passed parameter String message = getParameter(“message”); – Compile MessageApplet.java javac MessageApplet.java • Edit MessageApplet.html – Add the parameter tag between the <applet> and </applet> tags <param name=message value=“Hello Class!”> • Test the applet – appletviewer Name.html Georgia Institute of Technology Applet Methods • Applets inherit methods from the Applet class – – – – init() - initialize and set-up the applet start() - start execution of applet or restart stop() - stop execution of applet destroy() - clean up before termination Browser calls init to setup applet or on reload init() Stop is called when leaving the page or quitting. start() Start is called to start execution (applet visible) Georgia Institute of Technology stop() destroy() Final cleanup Run Applet Exercise • Use appletviewer to test the applet – Open a command prompt window – Start->Programs>Accessories->Command Prompt – Change to the correct directory – appletviewer RunApplet.html • Stop the applet • Start the applet • Restart the applet Georgia Institute of Technology Disadvantages to Applets • You must download the code from the server – user may have to wait • Using html, animated gifs, dhtml, and scripting may be easier for some tasks • Version problems with browsers – 3.0 browsers support Java 1.0.2 – 4.0 browsers support Java 1.1 – Need plug-in for 1.2 (only Sun and windows) • Security restrictions Georgia Institute of Technology Advantages to Applets • Code is downloaded from server – no distribution – no installation – users all on same version of code • Cross platform GUI environment • Multimedia support • The power of an object-oriented programming language • Create interactive and dynamic web pages Georgia Institute of Technology Applet Resources • Sun Tutorial for AWT style applets http://java.sun.com/docs/books/tutorial/applet/index.html • Sun tutorial for Swing style applets http://java.sun.com/docs/books/tutorial/uiswing/compone nts/applet.html • Applet Home Page http://java.sun.com/applets/ • Example Applet – Visual Human http://www.dhpc.adelaide.edu.au/projects/vishuman2/ Georgia Institute of Technology Summary • There are three kinds of comments in Java – // comment or /* comment */ or /** comment */ • The package statement is the first code in a class file. – package edu.gatech.ice; • Import statements follow the package statement. – import edu.gatech.edu.*; • The class definition follows the import statement. • Inside a class definition you declare attributes, constructors, and methods. Georgia Institute of Technology