Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008

advertisement
Java Source Anatomy
Barb Ericson
Georgia Institute of Technology
July 2008
SourceAnatomy
1
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
SourceAnatomy
2
Structure of a Java Source File
Optional Package statement
Optional Import statements
Comments (like author(s))
Class definition
{
Attributes - fields
Constructors - initializers
Methods - behaviors
Optional Main method
}
SourceAnatomy
3
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.
SourceAnatomy
4
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
SourceAnatomy
5
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;
SourceAnatomy
6
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 in your code
– java.awt.Color
SourceAnatomy
7
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
SourceAnatomy
8
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;
SourceAnatomy
9
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
SourceAnatomy
10
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 Tools and select Preview Javadoc for
Current Document
– Compare the html documentation to the original
Javadoc comments
SourceAnatomy
11
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
SourceAnatomy
12
Class Definition Examples
public class Person implements Comparable
{
attributes, methods, and inner classes
}
private class Helper extends Object
{
attributes, methods, and inner classes
}
SourceAnatomy
13
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
SourceAnatomy
14
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 Picture
objects know how to do?
• Where is the play method defined that Sound
objects know how to do?
SourceAnatomy
15
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
SourceAnatomy
16
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)
SourceAnatomy
17
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
SourceAnatomy
18
Attributes/Fields
• 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
SourceAnatomy
19
Attribute Exercise
• Open SimplePicture.java
• What are the attributes (fields)?
– Which are object fields?
– Which are class (static) 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);
SourceAnatomy
20
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
SourceAnatomy
21
Visibility Exercise
• Open SimplePicture.java
– Which fields have public visibility?
• Why are these public?
– Which fields have private visibility?
• Why are these private?
SourceAnatomy
22
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; }
}
SourceAnatomy
23
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
SourceAnatomy
24
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
SourceAnatomy
25
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?
SourceAnatomy
26
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;}
SourceAnatomy
27
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
SourceAnatomy
28
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)
SourceAnatomy
29
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
SourceAnatomy
30
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
SourceAnatomy
31
Summary
• 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.*;
• There are three kinds of comments in Java
– // comment or /* comment */ or /** comment */
• The class definition follows the import statement.
• Inside a class definition you declare attributes,
constructors, and methods.
SourceAnatomy
32
Download