Title: Introduction to Programming with Java
1Introduction to Programmingwith Java
2A Counter Class
public class Counter private int count
public Counter () count 0
public int getCount() return count
public void inc() count count 1
// add code for a reset method
state instance variable(s)
constructor(s)
methods
3How to Create Classes, Objects
- Type code for the class in DrJavas main pane
- Save the code in a file with the same name as the
class(e.g. Counter.java) - Compile it (choose the option to Save on Compile)
- Successful compilation creates an additional
.class file, which contains Java bytecode (e.g.
Counter.class) - Now you can create an object with the new
operator -
- gt Counter c1
- gt c1 new Counter()
- gt c1.inc()
4Each Object Has Its Own State
- gt Counter c1
- gt c1 new Counter()
- gt c1.getCount()
- 0
- gt c1.inc()
- gt c1.getCount()
- 1
- gt // create another counter
- gt Counter c2 new Counter()
- gt c2.getCount()
- 0
- gt c1.getCount()
- 1
5Anatomy of a Class
6What is a Method?
7What Can a Method Do?
- Change its objects state
- Report its objects state
- Operate on numbers, text, files, graphics, web
pages, hardware, - Create other objects
- Call another objects method obj.method(args)
- Call a method in the same classthis.method(args)
- Call itself (recursion)
- And much more, as well see!
Advanced A static method pertains to a class
vs. an individual object.
8Method Declaration
- public return_type methodName(0
parameters).. - public int getMiles() ..
- public void increaseSpeed(int accel, int
limit).. - Name Verb starting with a lowercase letter, with
camel caps - Ouput Return type required.
- Input 0 or more parameters
- Body
- Enclosed by curly braces
- Contains an arbitrary of statements
(assignment, if, return, etc.). - May contain local variable declarations
- How its called dot operator
- objectName.methodName(arguments)
- cab1.increaseSpeed(5, 65)
9Getter and Setter Methods
10A Methods Input
- A method may receive 0 or more inputs.
- A method specifies its expected inputs via a list
of formal parameters (type1 name1, type2 name2,
) - In a method call, the number, order, and type of
arguments must match the corresponding
parameters.
11Method Output
- A method may output nothing (void) or one thing.
- If it outputs nothing
- Its return type is void
- public void setMiles(int miles)..
- If it outputs one thing
- Its return type is non-void (e.g int, boolean,
Taxi) - public int getMiles()..
- It must have a return statement that returns a
value - // value returned must match return type
- return miles
12What is a Constructor?
13A Class with Two Constructors
14Constructor Method Review
15Anatomy of a Class