Packages Packages 1. Every Java object resides in a package . 2. An - - PowerPoint PPT Presentation
Packages Packages 1. Every Java object resides in a package . 2. An - - PowerPoint PPT Presentation
Packages Packages 1. Every Java object resides in a package . 2. An objects package is explicitly declared on the first line of code in a .java file: package edu.pcwe.uw.javaintro.misc; public class HelloWorld { public static void main(
Packages
- 1. Every Java object resides in a package.
- 2. An object’s package is explicitly declared on the first line
- f code in a .java file:
package edu.pcwe.uw.javaintro.misc; public class HelloWorld { public static void main( String[] args ) { System.out.println( "Hello world!" ); } }
Packages
- 3. The fully qualified name of a class includes its
package name; the fully qualified name of the class in the preceding slide is:
edu.pcwe.uw.javaintro.misc.HelloWorld
Packages
- 3. Packages allow different programming organizations
to choose the same class name without fear of confusion:
java.awt.List java.util.List
Packages
- 4. A .java file without a package statement is said to
reside in the default package. Note: We will not be using explicit packages for the code we write in this class. However you have to know a little bit about packages in order to use pre‐assembled code.
Libraries
- 1. A library is a collection of packages.
- 2. A library may reside in a dedicated directory…
- 3. … but is more commonly stored in a java archive
(.jar) file.
Libraries
- 4. To use an object from a library, you must:
a) Import the object from its package into your code:
import edu.uweo.javaintro.tools.Turtle;
b) Tell java where the library lives that contains the package:
Objects
Definition
- 1. An object stores information and performs actions.
- 2. An object has a name and a type.
- 3. The name of an object must be unique, and allows you to
have many objects of the same type.
- 4. The type of an object determines what it can store and what
it can do.
A java Integer object stores whole numbers; it can perform basic arithmetic, such as adding and subtracting. A Cartograph object might store the coordinates of cities, and be able to compute the distance between them.
Declaration
- 1. A declaration determines the name and type of an object:
Person cartman; ^ ^ ^ type name | end-declaration
- 2. Objects need to be created before you can use them:
cartman = new Person();
- 3. An object can be declared and created in one step:
Person cartman = new Person();
Methods
- 1. A method (a.k.a. function or procedure) is how you usually
interact with an object.
- 2. A method has a name and a type.
- 3. A method requires 0 or more arguments enclosed in
parentheses.
- 4. A method is invoked using the executor (a period).
Person cartmen = new Person(); cartman.takeAHike( 3, 2 ); ^ ^ ------ executor | ^ | arguments | name
Turtle Objects
Introduction
See also: Turtle Documentation on the class web site.
- 1. To work with the Turtle class you must import it from
edu.uweo.javaintro.tools.
- 2. A Turtle is an object that can draw simple figures.
- 3. A Turtle starts at the center of a blank screen facing “east.”
import edu.uweo.javaintro.tools.Turtle;
- or-
import edu.uweo.javaintro.tools.*;
A Turtle’s Habitat
The paint Method
The paint method draws a line and changes the position of a
- Turtle. It takes two arguments: angle and distance.
paint( angle, distance ) angle: Causes a turtle to turn a number of degrees; positive numbers turn left; negative numbers turn right. distance: Tells a turtle how many pixels to walk; positive numbers walk forward; negative numbers walk backward.
Painting (1)
Painting (2)
Painting (3)
Moving
The move Method
The move method changes the position of a Turtle without
- drawing. It takes two arguments: angle and distance.
move( angle, distance ) angle: Causes a turtle to turn a number of degrees; positive numbers turn left; negative numbers turn right. distance: Tells a turtle how many pixels to walk; positive numbers walk forward; negative numbers walk backward.
The swingAround Method
The swingAround method tells a turtle to draw a circle; it does not change the position of the turtle. It takes one argument: the radius of the circle.
swingAround( radius ) radius: Specifies the radius of the circle.
Swinging Around
Comments (1)
- Adding comments to your code can make it more readable;
the java compiler ignores comments.
- The double slash (//) begins a comment that continues to the
end of the line:
Turtle sue = new Turtle(); sue.paint( 45, 200 ); // start by drawing a diagonal line sue.move( -135, 300 ); // make sue face due south
Comments (2)
- Another kind of comment begins with slash-asterisk (/*) and
ends with asterisk-slash (*/):
/* This program renders a surrealistic sketch of a monkey eating a banana. Author: Jordan Alispiegal Date: 23-June-2008 */ public class Monkey { . . .
Exercises
Textbook, Chapter 1, page 1-5: Use an editor (notepad++) to enter the program TwoSquares from listing 1.2. Use javac to compile the program, and java to run it. Textbook, Chapter 1, page 1-7: Exercises 1.3, 1.5 and 1.7 (note: the house in exercise 1.7 should have a flat roof).
Parts of a Java Program
class + name
A class creates a new type, something which can contain data and define actions. In java, nothing can happen outside a class. Every class has a name, such as Turtle. class HelloWorld creates a new class named HelloWorld.
public class HelloWorld { /* body of class goes here */ }
matching braces must live in HelloWorld.java
public + class
Declaring a class to be public means that it can be used by
- anyone. There are other options, such as private, but we won't
be talking about those for a while.
public class HelloWorld { /* body of class goes here */ }
Braces
In java, braces are used to group things together. In the context
- f a class the left brace ({) signals the start of the class, and the
right brace (}) signals the end of the class. Braces are always used in pairs.
public class HelloWorld { public static void main( String[] args ) { System.out.println( "Hello World!" ); } }
main
When you start a java program with the java tool, you must designate the class to start executing. This class must have a block of code (called a method) named main, which must be written exactly as shown:
public static void main( String[] args )
public class HelloWorld { public static void main( String[] args ) { System.out.println( "Hello World!" ); } }
void
In Java, some methods can be used to calculate values, for example,
Math.abs is used to calculate the absolute value of a number: System.out.println( Math.abs( -3 ) );
When a method does not calculate a value, it must be declared void.
public class HelloWorld { // main does not calculate a value. public static void main( String[] args ) { System.out.println( "Hello World!" ); } }
public method-name
In Java, some methods can be used by anyone, while access to
- ther methods is restricted. A method declared public can be
used by anyone. There are other options, such as private which we’ll talk about later.
public class HelloWorld { public static void main( String[] args ) { System.out.println( "Hello World!" ); } }
static method-name
In Java, some methods can be used anytime, but others can only be used after you create an object (you can’t tell a Turtle to draw anything until you create one). static methods, on the other hand, can be used whether you have an object or not.
public class HelloWorld { public static void main( String[] args ) { System.out.println( "Hello World!" ); } }
String[] args
String[] args is used to process command line arguments.
Don’t worry about that right now; just remember that your main method must be declared this way.
public class HelloWorld { public static void main( String[] args ) { System.out.println( "Hello World!" ); } }
Spacing
Spaces and line breaks are (usually) optional in Java code. We use them to make our code more readable.
public class HelloWorld{public static void main(String[]args){“Hello World”);}}
Indentation
Indentation is optional in Java code, but it makes your programs much easier to read. Put the braces that delimit a block of code
- n lines by themselves, and line them up with the start of the
- block. Inside the block indent four spaces.
public class HelloWorld { public static void main( String[] args ) { System.out.println( "Hello World!" ); } }
Exercises (1 of 2)
1. Go into your HelloWorld program and change main to sam. Compile it with the javac command. What happens when you try to run it with the java command? (Before you forget, change sam back to main.) 2. Add the getGreeting method to your HelloWorld program, and change the "HelloWorld" line as follows:
public class HelloWorld { public static void main( String[] args ) { System.out.println( getGreeting() ); } public static String getGreeting() { return "Hi there, world"; } } (continued on next slide)
Exercises (2 of 2)
(continued) Compile and run the program. Explain:
- What happened when you substituted getGreeting() for "HelloWorld"?
- What is the purpose of String in the line public static String getGreeting()?
3. Download and complete TweedleActivity from the class web site.
Introduction to Inheritance (1)
You can create a new class that inherits data and behavior from an existing class by using the extends expression:
import edu.uweo.javaintro.tools.Turtle; public class Bob extends Turtle { public void whoAreYou() { System.out.println( "I am Bob, the Turtle." ); System.out.println( "Don't mess with me." ); } }
Introduction to Inheritance (2)
In the above example, an object of type Bob can do anything a Turtle can. In fact, it is a Turtle, plus a little more:
public class Test { public static void main( String[] args ) { Bob fred = new Bob(); fred.paint( 0, 128 ); fred.whoAreYou(); } }
The SmartTurtle Class
The SmartTurtle class extends Turtle by adding two new methods.
public class SmartTurtle extends Turtle { public void makeSmallSquare() { paint( 90, 10 ); paint( 90, 10 ); paint( 90, 10 ); paint( 90, 10 ); } public void makeBigSquare() { paint( 90, 40 ); paint( 90, 40 ); paint( 90, 40 ); paint( 90, 40 ); } } Questions: 1. Why are the new methods public? 2. Why are they not not not not static? 3. Why do we use the command paint and not something.paint?
Instance Methods (1)
1. An instance method can only be executed on a specific object. 2. An instance method is declared without the word static. 3. Inside the method, a command like paint refers to the object the method was executed on ... 4. ... this is called the default executor.
Instance Methods (2)
When we write smarty.makeBigSquare() the paint command in makeBigSquare is executed by smarty; when we write iggy.makeSmallSquare() the paint command is executed by iggy.
public class Test { public static void main(String[] args) { SmartTurtle smarty = new SmartTurtle(); SmartTurtle iggy = new SmartTurtle(); smarty.move( 0, -100 ); smarty.makeBigSquare(); iggy.move( 0, 100 ); iggy.makeSmallSquare(); } }
The Default Executor
In an instance method, the default executor can be explicitly invoked using this.
public void makeSmallSquare() { paint( 90, 10 ); paint( 90, 10 ); paint( 90, 10 ); paint( 90, 10 ); } // is equivalent to public void makeSmallSquare() { this.paint( 90, 10 ); this.paint( 90, 10 ); this.paint( 90, 10 ); this.paint( 90, 10 ); }
Definitions
Instance An object that belongs to some class is an instance of that class. An object can be an instance of more than one class; a SmartTurtle object is an instance of both the Turtle and SmartTurtle classes. Subclass When class A inherits from class B, class A is said to be a subclass of class B. Superclass When class A inherits from class B, class B is said to be a superclass of class A.
public class A extends B
Exercises
- Textbook, Chapter 1, page 1-8:
Create the file SmartTurtle.java, and enter the code from Listing 1.3. Compile the code.
- Textbook, Chapter 1, page 1-11:
Exercises 1.8, 1.10, 1.11, 1.14
Turtles: the switchTo Method
The switchTo method takes one argument, a color defined in the Turtle class.
switchTo( color ) color: a color from the Turtle class. Example: Turtle fred = new Turtle(); fred.switchTo( Turtle.RED );
Turtles: Constants
Data stored in a class can include constant values (they're called constants because they can't be changed). The Turtle class has several constants used to represent colors:
– Turtle.BLACK – Turtle.GRAY – Turtle.BLUE – Turtle.GREEN – Turtle.RED – Turtle.YELLOW – Turtle.ORANGE – Turtle.PINK – Turtle.MAGENTA – Turtle.WHITE
Turtles: the fillCircle Method
The fillCircle method takes one argument, a number that designates the radius of a solid circle to draw.
fillCircle( radius ) radius: the radius of a circle. Example: Turtle fred = new Turtle(); fred.switchTo( Turtle.RED ); fred.fillCircle( 64 );
Turtles: the fillBox Method
The fillBox method takes two arguments, numbers that designates the width and height of a solid rectangle to draw.
fillBox( width, height ) width: the width of a rectangle height: the height of a rectangle Example: Turtle fred = new Turtle(); fred.switchTo( Turtle.RED ); fred.fillBox( 128, 32 );
Turtles: the say Method
The say method takes one argument, a string to draw at the Turtle’s current position.
say( string ) string: string to draw Example: Turtle fred = new Turtle(); fred.paint( 0, 200 ); fred.say( "making a right turn" ); fred.paint( -90, 200 );
Methods Without Objects
1. Methods that can be executed without an object are declared static:
public static void sleep( int milliseconds )
2. To execute a method that doesn’t need an object, use the class name:
Turtle.sleep( 500 )
Turtles: the Sleep Method
The sleep method takes one argument, the number of milliseconds for a Turtle to pause between commands.
static void sleep( millis ) str: the number of milliseconds to sleep. Example: Turtle fred = new Turtle(); fred.paint( 90, 128 ); Turtle.sleep( 2000 ); //pause for two seconds fred.paint( 90, 64 );
Keywords
A keyword is a part of the java programming language. Some examples of keywords that you have already seen are:
public class static void extends new
There are many others, including if, else, for, while and interface.
Identifers
An identifier is a name that you give to a programming component that you create, including class names (Turtle) method names (makeSmallSquare) and
- bjects (Turtle fred = new Turtle()). Rules for creating identifiers are:
You may not use a keyword. The identifier must begin with a letter or underscore. After the first character, you may use letters, numbers and underscores. Capitalization counts; Fred is different from fred.
Java conventions that you should follow:
Class names should begin with an upper case letter. Non-constant object and method names should begin with a lower case letter. Constant names should not include lower case letters. Identifiers should not begin with an underscore.
Exercises
- Which of the following are keywords that you have encountered in class?
public class fred wilma Turtle void paint static
- Which of the following are valid identifiers?
fred _wilma ted_90 9_ted static void ___9_5___a_ _9%
- Write a program that tells a Turtle to draw a line 100 pixels long, then say “100”; extend the
line by another 100 pixels and say “200”.
- Textbook, Chapter 1, page 1-16:
Exercises 1.18, 1.21
- OPTIONAL:
Textbook, Chapter 1, page 1-30: Write, compile and run the program in Listing 1.11.