Java Fundamentals: The Java Language
Introduction and Setting up Your Environment
Jim Wilson
@hedgehogjim | blog.jwhh.com | jimw@jwhh.com
What to Expect in This Course
Strong foundation in Java syntax, constructs,
Hands-on
the Java language concepts, and usage
Language skills to work effectively in any Java-based environment
Java SE Java EE JavaFX Java ME Android
What to Expect in This Module
Brief Java overview
JRE vs. JDK
Setting up your environment
Choosing a Java IDE
What Is Java?
Java
Programming Language
Syntax Control flow
Data types Object-orientated
Java SE
Java EE
Runtime Environment Java ME
Configuration JavaFX
Threading
Security Input/output
Android
What Is Java?
Java
Programming Language This course!
Syntax Control flow
Data types Object-orientated
Runtime Environment
Configuration Threading
Java Fundamentals:
Security Input/output
The Java Environment
JRE vs. JDK
Java Runtime Environment (JRE) Java Development Kit (JDK)
Required to run Java apps Provides tools required to
End-users normally create Java apps
require only the JRE Developers normally
require the JDK
JDK installation
includes JRE
Creating and Running Java Apps
Java Development Kit Java App
Tools (platform-independent byte codes)
Java Runtime Environment
xyz.java
Host Environment
(Windows / Linux / Mac / Browser / Android)
Demo
Setting up the JDK
Latest version of JDK available at
http://bit.ly/psjdkdownload
JDK May be labeled “Java Platform”
Integrated Development Environment (IDE)
Many choices!
Both available for free
NetBeans IDE
Provided by Oracle for free
Available with support for Java SE/EE/ME
and JavaFX at no extra cost
Does not support Android
An installer containing the JDK and the
Java SE bundle of NetBeans is available
IntelliJ IDEA Community Edition
Free version of a commercial product
Supports Java SE and Android
Projects compatible w/ commercial version
(adds Java EE, server debugging, etc.)
Demo
Setting up NetBeans IDE
Available with the JDK at
http://bit.ly/psjdkdownload
Available stand-alone with varying Java
platform support at
https://netbeans.org/downloads
Demo
Setting up IntelliJ IDEA Community Edition
Latest version available at
http://bit.ly/intellijdownload
Summary
Java is a language and a runtime environment
- Specific environment features may vary (Java SE/ME/EE, JavaFX, Android)
- Language remains pretty consistent
End-users require the Java Runtime Environment (JRE)
Developers require the Java Development Kit (JDK)
Many Integrated Development Environments (IDE) are available
- Pick the one you like best
Creating a Simple App
Jim Wilson
@hedgehogjim | blog.jwhh.com | jimw@jwhh.com
What to Expect in This Module
Creating your first IntelliJ project
Running programs from the command line
Statement and comment syntax
Introduce packages
Creating and running a NetBeans project
Demo
Creating Your First IntelliJ Project
Demo
Running Programs from the Command Line
Statement Structure
Programs made up of statements
Statements end with a semicolon
System.out.println( “Hello World” ) ;
Parts separated by zero or
more whitespace
Space
Tab
Newline
Statement Whitespace
System.out.println(“Hello World”);
System.out.println
(
“Hello World”
System.out.println ( “Hello World” );
)
;
System.out.println( “Hello World”) ;
Comments
Using comments Types of comments
Add human-readable Line comments
notes to source code //
“Hide” source code Block comments
without deleting /* … */
JavaDoc comments
/** … */
Demo
Comments
Introducing Packages
package com.pluralsight.example; Packages provide organization
public class Main { Follow standard naming
public static void main(Strings[] args) {
} Affect source code file structure
}
Package Naming Conventions
Use reversed Add further qualifiers
All lowercase to assure uniqueness
domain name to assure within a
global uniqueness company/group
package com.pluralsight.myproject;
package com.pluralsight.accounting.myproject;
package com.pluralsight.coursemgmt.myproject;
Members Become Part of the Package
package com.pluralsight.myproject;
Main
public class Main {
public static void main(Strings[] args) { com.pluralsight.myproject.Main
}
}
Package Name and Source File Structure
Java requires no correlation But most IDE’s require a
between package names sub-folder for each part of the
and source code file structure package name
Main.java src
Main. com
package ccoomm.pluralsight.example; java
public class Main { pluralsight
public static void main(Strings[] args) {
example
}
}
Main.java
Demo
Packages
Demo
Creating and Running a NetBeans Project
Summary
Execute programs from the command line with the “java” command
- Remember to use the full class name including the package name
- On Windows must include JRE bin folder in Path environment variable
Programs are made up of statements
- Statements end with a semicolon
- Parts separated by zero or more whitespaces
Use comments to add notes and hide statements from the compiler
Packages provide organization
- Assure uniqueness
- Most IDE’s tie source code file structure to package names
Variables, Data Types, and Math Operators
Jim Wilson
@hedgehogjim | blog.jwhh.com | jimw@jwhh.com
What to Expect in This Module
Variables
Primitive data types
Arithmetic operators
Type conversion
Variables
Named data storage Strongly typed Value can be modified
int dataValue;
dataValue =
100;
int myInfo = 200;
Naming Variables
Variable naming is based on a combination of rules and conventions
- Rules allow the use of letters, numbers, $ and _
• By convention only letters and numbers are used
- Rules require that first character is not a number
• By convention it is always a letter
- By convention follow the style often referred to as “Camel Case”
• First letter is lower case
• Start of each word after the first is upper case int total;
int
• All other letters are lower case
grade4;
int bankAccountBalance;
int level2Training;
Using Variables
public class Main {
public static void main(Strings[] args) {
int myVar;
System.out.println(myVar); Error
myVar = 50;
System.out.println(myVar); 50
int anotherVar = 100;
System.out.println(anotherVar); 100
myVar = anotherVar;
System.out.println(myVar); 100
anotherVar = 200;
System.out.println(anotherVar); 200
}
System.out.println(myVar);
100
}
Primitive Data Types
Built into the Foundation of all Four categories of
language other types primitive types
• Integer
• Floating point
• Character
• Boolean
Integer Types
Type Size Min Value Max Value Literal Format
(bits)
byte 8 -128 127 0
short 16 -32768 32767 0
int 32 -2147483648 2147483647 0
long 64 -9223372036854775808 9223372036854775807 0L
byte numberOfEnglishLetters = 26;
short feetInAMile = 5283;
int milesToSun = 92960000;
long nationalDebt = 18100000000000L;
Floating Point Types
Implementation of IEEE 754 floating point standard
Stores values containing a fractional portion
Supports positive, negative, and zero values
Type Size Smallest Positive Largest Positive Value Literal Format
(bits) Value
float 32 1.4 x 10-45 3.4 x 1038 0.0f
double 64 4.9 x 10-324 1.7 x 10308 0.0 or 0.0d
float milesInAMarathon = 26.2f;
double atomWidthInMeters= 0.0000000001d;
Character and Boolean Types
The char type stores a single Unicode character
- Literal values placed between single quotes
- For Unicode code points, use \u followed by 4-digit hex value
char regularU = 'U';
char accentedU = '\u00DA'; // Ú
The boolean type stores true/false values
- Literal values are true and false
boolean iLoveJava = true;
Primitive Types Are Stored By-value
otherValue firstValue
int firstValue = 100;
100 15000
int otherValue = firstValue;
firstValue = 50;
Arithmetic Operators
Prefix/postfix Compound
Basic operators
operators assignment operators
Basic Math Operators
Operator Floating Point Example Integer Example
Add + 1.0 + 2.0 3.0 1 +2 3
Subtract - 5.0 - 4.0 1.0 5 -4 1
Multiply * 4.0 * 2.0 8.0 4 *2 8
Divide / 13.0 / 5.0 2.6 13 / 5 2
Modulus % 13.0 % 5.0 3.0 13 % 5 3
Prefix / Postfix Operators
++ increments value by 1 int myVal = 5;
System.out.println(++myVal); 6
-- decrements value by 1 System.out.println(myVal); 6
As prefix applies operation before
returning value
int myVal = 5;
As postfix applies operation after System.out.println(myVal++); 5
returning value System.out.println(myVal); 6
Compound Assignment Operators
int myVal = 50;
myVal -= 5;
Combines an operation and
assignment
System.out.println(myVal); 45
Applies result of right side to left side
Stores that result in variable on left side
int result = 100;
Available for 5 basic math operators
int val1 = 5;
+= -= *= /= %=
int val2 = 10;
/= val1 * val2;50
result / 100
System.out.println(result); 2
Operator Precedence
Operators are evaluated in a well-
defined order
Postfix x++ x--
Operators of equal precedence are Prefix ++x --x
evaluated left-to-right Multiplicative */ %
Can override precedence with Additive + -
parenthesis
Nested parenthesis evaluated from the
inside out
Demo
Operator Precedence
Type Conversion
Implicit type conversion Explicit type conversion
Conversions performed Conversions performed
automatically by the explicitly in code with cast
compiler operator
int iVal = 50; long lVal = 50;
long lVal = iVal; int iVal = (int) lVal;
Implicit Type Conversion
Widening conversions are automatic
Mixed integer sizes
Uses largest integer in equation
Mixed floating point sizes
Uses double
Mixed integer and floating point
Uses largest floating point in equation
Explicit Type Conversion
Can performing widening and narrowing
Floating point to integer drops fraction
Use caution with narrowing conversions
Integer to floating point can lose precision
Demo
Type Conversion
Summary
Variables are strongly typed in Java
Primitive types
- Integer types, floating point types, char type, boolean type
Math operators
- Basic operators, postfix/prefix operators, compound assignment operators
Math operators follow a well-defined order of precedence
Type conversions
- Compiler can automatically apply widening type conversions
- Use type casting to explicitly perform type conversions
Conditional Logic, Looping, and Arrays
Jim Wilson
@hedgehogjim | blog.jwhh.com | jimw@jwhh.com
What to Expect in This Module
Conditional logic
Basic looping
Arrays
For-each loop
The switch statement
Conditional Logic
Relational operators
Conditional assignments
The if statement
Logical operators
Relational Operators
Operator Integer, Character Boolean
Floating Point Example Example
Example
Greater than > 5 > 4 ‘c’ > ‘a’ not available
5 >= 4 ‘c’ >= ‘a’
Greater than or equal to >= not available
4 >= 4 ‘a’ >= ‘a’
Less than < 4 < 5 ‘a’ < ‘c’ not available
4 <= 5 ‘a’ <= ‘c’
Less than or equal to <= not available
4 <= 4 ‘a’ <= ‘a’
true == true
Equal to == 5 == 5 ‘c’ == ‘c’
false == false
Not equal to != 4 != 5 ‘a’ != ‘c’ true != false
Conditional Assignment
Assign a value to a variable based on the
result of a condition int v1 = 7;
int v2 = 5;
int vMax = v1 > v2 ? v1 : v2;
result = condition ? true-value : false-value ;
System.out.println(vMax); 7
float students = 30;
float rooms = 4;
float studentsPerRoom = rooms == 0.0f ? 0.0f : students/rooms;
System.out.println(studentsPerRoom); 7.5
If-else Statement
An if statement conditionally executes
a statement
if (condition ) int v1 = 10;
true-statement ; int v2 = 4;
else if(v1 > v2)
false-statement ;
System.out.println(“v1 is bigger”);
The optional else clause executes a else
System.out.println(“v1 is NOT bigger”);
statement when the if condition is false
Chaining if-else Statements
If-else statements chained together are evaluated in order until one is true
if (condition-1 ) int v1 = 10;
true-statement-1 ;
int v2 = 40;
else if ( condition-2 )
true-statement-2 ; if(v1 > v2)
. System.out.println(“v1 is bigger”);
.
. else if(v1 < v2)
else if ( condition-N ) System.out.println(“v2 is bigger”);
true-statement-N ; else
System.out.println(“v1 and v2 are equal”);
else
false-statement ;
Block Statements
A block statement groups statements into a compound statement
{ int v1 = 10, v2 = 4, diff;
statement-1; if(v1 > v2) {
statement-2; diff = v1 – v2;
. System.out.println(“v1 is bigger”);
.
. System.out.println(diff);
statement-N; }
} else if(v2 > v1) {
diff = v2 – v1;
System.out.println(“v2 is bigger”);
System.out.println(diff);
}
else
System.out.println(“v1 and v2 are equal”);
Demo
Nested if-statements
if( ... )
if( ... )
Block Statements and Variable Scope
A variable declared within a block is
float students = 30.0;
not visible outside of the block float rooms = 4.0;
- A variable’s range of visibility is known
as the variable’s scope if(rooms > 0.0) {
System.out.println(students);
System.out.println(rooms);
float avg = students / rooms;
System.out.println(avg);
Logical Operators
Operator What Resolves to True
And & true & true
Or | false | true true | false true | true
Exclusive or (XOR) ^ false ^ true true ^ false
Negation ! false
int a = 20, b = 14, c = 5; boolean done = false;
true true
true true if (!done)
if (a > b & b > c)
System.out.println(“Keep going");
System.out.println(“a is greater than c");
Conditional Logical Operators
Operator What Resolves to True
Conditional and && true && true
Conditional or || false || true true || ----
Resolve following conceptually similar rules as non-conditional and/or
Only execute the right-side if needed to determine the result
- && only executes right-side if left-side is true
- || only executes right-side if left-side is false
Demo
Logical And vs. Conditional Logical And
& vs. &&
Demo
CalcEngine
Looping
While loop Do-while loop For loop
While Loop
Repeatedly executes a statement as
long as the condition is true while (condition )
- Condition checked at loop start statement ;
- Statement may never execute
int kVal = 5;
int factorial = 1;
int kVal = 5;
int factorial = 1; while(kVal > 1) {
while(kVal > 1) factorial *= kVal;
kVal -= 1;
factorial *= kVal--;
}
System.out.println(factorial); System.out.println(factorial);
Do-while Loop
Repeatedly executes a statement as do
long as the condition is true statement ;
while (condition );
- Condition checked at loop end
- Statement always executes at least once
int iVal = 155;0;
do { 5 * 2 = 10
System.out.print(iVal);
10 * 2 = 20
System.out.print(“ * 2 = ”);
20 * 2 = 40 150 * 2 = 300
iVal *= 2;
System.out.println(iVal); 40 * 2 = 80
} while(iVal < 100); 80 * 2 = 160
For Loop
Repeatedly executes a statement as
long as the condition is true
for (initialize ; condition ; update )
- Condition checked at loop start statement ;
- Provides simplified notation for loop
control values
int iVal = 1;
while(iVal < 100) {
for( int iVal = 1; iVal < 100; iVal *= 2 ) {
System.out.println(iVal); System.out.println(iVal);
ival *= 2; }
}
Arrays
theVals
Provides an ordered collection of 10.0f 20.0f 15.0f
elements
0 1 2
- Each element accessed via an index
float[] theVals = new float[3];
- Indexes range from 0 to number-of-
elements minus 1 theVals[0] = 10.0f;
theVals[1] = 20.0f;
- Number of elements can be found via
theVals[2] = 15.0f;
array’s length value
float sum = 0.0f;
for(int i = 0; i < theVals.length; i++)
sum += theVals[i];
System.out.println(sum);
Arrays
theVals
Provides an ordered collection of 10.0f 20.0f 15.0f
elements
0 1 2
- Each element accessed via an index
float[] theVals = { 10.0f, 20.0f, 15.0f };
- Indexes range from 0 to number-of-
elements minus 1
- Number of elements can be found via
array’s length value
float sum = 0.0f;
for(int i = 0; i < theVals.length; i++)
sum += theVals[i];
System.out.println(sum);
For-each Loop
Executes a statement once for each
member in an array for (loop-variable-declaration :array )
- Handles getting collection length statement ;
- Handles accessing each value
float[] theVals = { 10.0f, 20.0f, 15.0f };
float sum = 0.0f;
for( float currentVal : theVals) {
sum += currentVal;
}
System.out.println(sum);
Switch
Transfers control to a statement based on a value switch (test-value ) {
- Simplifies testing against multiple possible case value-1:
matches statements
- Only primitive types supported are char and case value-2:
integers statements
.
.
- A match can execute more than one statement .
- Use break to avoid “falling through” case value-n:
- Can optionally include default to handle any statements
unmatched values default:
statements
}
Switch Example
int iVal = 2
150;
switch(iVal % 2) {
case 0: 10 is even
System.out.print(iVal);
10 is odd
System.out.println(“ is even”);
break; oops it
case 1: broke
System.out.print(iVal);
System.out.println(“ is odd”); 10 is even
break;
default:
System.out.println(“oops it broke”); 25 is odd
break;
}
Demo
CalcEngine with Arrays, Loop, and Switch
Summary
Use the if-else statement to provide conditional logic
- If-else statements can be chained together
Block statements use brackets to group statements
- Variables declared within a block are not visible outside of the block
Both while and do-while loops execute as long as a condition is true
- The do-while loop body always executes at least once
The for loop provides simplified notation for loop initialization and control
For-each statement handles details of executing once for each array member
Switch statement simplifies notation of testing against multiple matches
Representing Complex Types with Classes
Jim Wilson
@hedgehogjim | blog.jwhh.com | jimw@jwhh.com
What to Expect in This Module
Classes
Using classes
Classes as reference types
Encapsulation and access modifiers
Method basics
Field accessors and mutators
Classes in Java
Java is an object-oriented language
Objects encapsulates data, operations,
and usage semantics
- Allows storage and manipulation details
to be hidden
- Separates “what” is to be done from
“how” it is done
Classes provide a structure for
describing and creating objects
Classes
Flight.java
A class is a template for creating an object class Flight {
- Declared with the class keyword followed by
the class name
- Java source file name normally has same
name as the class
• We’ll talk more about this shortly
- Body of the class is contained within brackets
}
Classes
Flight.java
A class is made up of both state and class Flight {
executable code int passengers;
- Fields int seats;
• Store object state Flight() {
- Methods seats = 150;
passengers = 0;
• Executable code that manipulates state and }
performs operations
void add1Passenger() {
- Constructors if(passengers < seats)
• Executable code used during object passengers += 1;
}
creation to set the initial state
}
Using Classes
passengers
Use the new keyword to create a class 0
instance (a.k.a. an object) nycToSf
seats
- Allocates the memory described by
the class 150
slcToDallas
- Returns a reference to the allocated
memory
passengers
Flight nycToSf; 10
nycToSf = new Flight();
seats
Flight slcToDallas = new Flight();
150
slcToDallas.add1Passenger();
Classes Are Reference Types
passengers
Flight flight1 = new Flight(); 1
2
0
flight1
Flight flight2 = new Flight(); seats
flight2.add1Passenger(); 150
System.out.println(flight2.passengers); 1 flight2
flight2 = flight1;
System.out.println(flight2.passengers); 0 passengers
flight1.add1Passenger(); 10
flight1.add1Passenger();
seats
System.out.println(flight2.passengers); 2 150
Encapsulation and Access Modifiers
The internal representation of an object is generally hidden
This concept is known as Java uses access moditfoieraschieve
encapsulation encapsulation
Basic Access Modifiers
Modifier Visibility Usable Usable
on on
Classes Members
no access modifier Only within its own package Y Y
(a.k.a. package private)
public Everywhere Y Y
private Only within its own class N* Y
* As private applies to top-level classes;
private is available to nested-classes
Applying Access Modifiers
public class Flight {
pri vate int passengers;
pri vate int seats;
public Flight() {
seats = 150;
passengers = 0;
Flight flight1 = new Flight(); }
System.out.println(flight1.passengers); public void add1Passenger() { Flight.java
if(passengers < seats)
flight1.add1Passenger(); passengers += 1;
flight1.handleTooMany(); else
handleTooMany();
}
private void handleTooMany() {
System.out.println(“Too many”);
}
}
Naming Classes
Class names follow the same rules as variable names
Class name conventions are similar to variables with some differences
- Use only letters and numbers
- First character is always a letter class BankAccount { ... }
- Follow the style often referred to as “Pascal Case” class Person { ... }
• Start of each word, including the first, is upper case class TrainingVideo { ... }
• All other letters are lower case class URL { ... }
- Use simple, descriptive nouns
- Avoid abbreviations unless abbreviation’s use is more common than full name
Method Basics
Executable code that manipulates state return-type name ( typed-parameter-list ) {
statements
and performs operations
}
- Name
• Same rules and conventions as variables
• Should be a verb or action
- Return type void showSum (float x , float y, int count) {
• Use void when no value returned float sum = x + y;
- Typed parameter list for(int i = 0; i < count; i++)
• Can be empty System.out.println(sum);
}
- Body contained with brackets
Method Basics
Executable code that manipulates state MyClass m = new MyClass();
and performs operations m.showSum(7.5, 1.4, 3); 8.9
8.9
- Name 8.9
• Same rules and conventions as variables
• Should be a verb or action public class MyClass {
- Return type public void showSum (float x , float y, int count) {
• Use void when no value returned float sum = x + y;
- Typed parameter list for(int i = 0; i < count; i++)
• Can be empty System.out.println(sum);
}
- Body contained with brackets
}
Exiting from a Method
A method exits for one of MyClass m = new MyClass();
three reasons m.showSum(7.5, 1.4, 3); 8.9
8.9
- The end of the method is reached System.out.println(“II’’mm bbaacckk”); 8.9
- A return statement is encountered
- An error occurs
Unless there’s an error, control void showSum(float x, float y, int count) {
returns to the method caller float sum = x + y;
for(int i = 0; i < count; i++)
System.out.println(sum)
;
return;
}
Exiting from a Method
A method exits for one of MyClass m = new MyClass();
three reasons m.showSum(7.5, 1.4, 0
3);
- The end of the method is reached System.out.println(“II’’mm bbaacckk”);
- A return statement is encountered
- An error occurs if(count < 1)
Unless there’s an error, control void shroewtSuurmn(;float x, float y, int count) {
returns to the method caller float sum = x + y;
for(int i = 0; i < count; i++)
System.out.println(sum);
return;
}
Method Return Values
A method returns a single value public class Flight {
private int passengers;
- A primitive value private int seats;
// constructor and other methods elided for clarity
- A reference to an object public boolean hasRoom(Flight f2) {
- A reference to an array int total = passengers + f2.passengers;
if (total <= seats)
• Arrays are objects return true;
else
return false;
}
}
Method Return Values
A method returns a single value public class Flight {
private int passengers;
- A primitive value private int seats;
// constructor and other methods elided for clarity
- A reference to an object public boolean hasRoom(Flight f2) {
- A reference to an array int total = passengers + f2.passengers;
return total <= seats;
• Arrays are objects
}
Method Return Values
A method returns a single value public class Flight {
private int passengers;
- A primitive value private int seats;
// constructor and other methods elided for clarity
- A reference to an object public boolean hasRoom(Flight f2) {
- A reference to an array int total = passengers + f2.passengers;
return total <= seats;
• Arrays are objects }
public Flight createNewWithBoth(Flight f2)
{ Flight newFlight = new Flight();
newFlight.seats = seats;
newFlight.passengers = passengers + f2.passengers;
return newFlight;
}
}
Method Return Values
public class Flight {
Flight lax1 = new Flight(); private int passengers;
Flight lax2 = new Flight(); private int seats;
// constructor and other methods elided for clarity
// add passengers to both flights
public boolean hasRoom(Flight f2) {
int total = passengers + f2.passengers;
Flight lax3;
return total <= seats;
if(lax1.hasRoom(lax2)) }
lax3 =
public Flight createNewWithBoth(Flight f2)
lax1.createNewWithBoth(lax2);
{ Flight newFlight = new Flight();
newFlight.seats = seats;
newFlight.passengers = passengers + f2.passengers;
return newFlight;
}
}
Special References: this and null
Java provides special references
with predefined meanings
- this is an implicit reference to the public class Flight {
private int passengers;
current object private int seats;
• Useful for reducing ambiguity // constructor and other methods elided for clarity
• Allows an object to pass itself as a public boolean hasRoom(Flight f2) {
parameter ass.
int total = thpi sengers + f2.passengers;
return total <= seats;
- null is a reference literal }
}
• Represents an uncreated object
• Can be assigned to any reference
variable
Special References: this and null
Java provides special references
Flight lax1 = new Flight();
with predefined meanings
Flight lax2 = new Flight();
- this is an implicit reference to the // add passengers to both flights
current object
• Useful for reducing ambiguity Flight lax3;= null;
• Allows an object to pass itself as a if(lax1.hasRoom(lax2))
parameter lax3 =
- null is a reference literal lax1.createNewWithBoth(lax2);
• Represents an uncreated object // do some other work
• Can be assigned to any reference if(lax3 != null)
variable
System.out.println(“Flights combined”);
Demo
CalcEngine with Classes and Methods
Field Encapsulation
In most cases, a class’ fields should not be directly
accessible outside of the class
Helps to hide Use methods to
implementation details control field access
Accessors and Mutators
public class Flight {
Use the accessor/mutator pattern private int passengers;
private int seats;
to control field access // other members elided for clarity
- Accessor retrieves field value
public int getSeats() {
• Also called getter return seats;
• Method name: getFieldName }
- Mutator modifies field value public void setSeats(int seats) {
• Also called setter this.seats = seats;
• Method name: setFieldName }
}
Accessors and Mutators
public class Flight {
private int passengers;
private int seats;
// other members elided for clarity
public int getSeats() {
Flight slcToNyc = new Flight();
return seats;
slcToNyc.setSeats(150); }
System.out.println(slcToNyc.getSeats()); 150
public void setSeats(int seats)
{ this.seats = seats;
}
}
Demo
CalcEngine with Accessors and Mutators
Summary
A class is a template for creating an object
- Declared with class keyword
- Class instances (a.k.a. objects) allocated with new keyword
Classes are reference types
Use access modifiers to control encapsulation
Methods manipulate state and perform operations
- Use return keyword to exit and/or return a value
Fields store object state
- Interaction normally controlled through accessors(getters) and mutators(setters)
Class Initializers and Constructors
Jim Wilson
@hedgehogjim | blog.jwhh.com | jimw@jwhh.com
What to Expect in This Module
Establishing initial state
Field Initializers
Constructors
Constructor chaining & visibility
Initialization blocks
Initialization and construction order
Establishing Initial State
When an object is created, it is expected to be in a useful state
Often the default state The object may need
established by Java is not enough to set values or execute code
Mechanisms for Establishing Initial State
Java provides 3 mechanisms for establishing initial state
Field initializers Constructors Initialization blocks
Field Initial State
A field’s initial state is established as part of object construction
Fields receive a “zero” value by default
byte float char boolean Reference
short double types
int
long
0 0.0 ‘\u0000’ false null
You don’t have to accept the default value
Field Initializers
Allow you to specify a field’s initial value as part of its declaration
- Can be a simple assignment
- Can be an equation
- Can reference other fields public class Earth {
long circumferenceInMiles;= 24901;
- Can be a method call long circumferenceInKilometers =
Math(.l
ron
ugn)
d( circumfe(
rleo
nncg
e)I(
nM2i4l9e0s1 * 1.6d )
;;
}
Constructor
Executable code used during object
public class Flight {
creation to set the initial state private int passengers;
- Have no return type private int seats;
public Flight() {
- Every class has at least one constructor seats = 150;
passengers = 0;
}
// other members elided for clarity
}
Constructor
Executable code used during object public class Passenger {
private int checkedBags;
creation to set the initial state private int freeBags;
- Have no return type // accessors & mutators elided for clarity
- Every class has at least one constructor private double perBagFee;
public Passenger() { }
• If no explicit constructors, Java provides one
}
- A class can have multiple constructors public Passenger(int freeBags) {
this.freeBags = freeBags;
• Each with a different parameter list
}
Passenger bob = new Passenger();
bob.setCheckedBags(3);
Passenger jane = new Passenger(2); }
jane.setCheckedBags(3);
Chaining Constructors
public class Passenger {
One constructor can call another // fields & methods elided for clarity
- Use the this keyword followed by public Passenger() {
parameter list }
- Must be the first line public Passenger(int freeBags) {
this.freeBags = freeBags;
}
public Passenger(int freeBags, int checkedBags) {
tthhiiss(
.freeBags);
= freeBags;
Passenger jane = new Passenger(2);
this.checkedBags = checkedBags;
jane.setCheckedBags(3); }
Passenger jane = new Passenger(2, 3);
}
Constructor Visibility
public class Passenger {
Use access modifiers to control // fields & methods elided for clarity
constructor visibility public Passenger() {
- Limits what code can perform }
specific creations public Passenger(int freeBags) {
h is
th s.
(freeBags >
= 1
fr?
ee2
B5 .s
ag 0d
; : 50.0d);
}
public Passenger(int freeBags, int checkedBags) {
Passenger cheapJoe = new Passenger(0.01d); this(freeBags);
this.checkedBags = checkedBags;
Passenger fred = new Passenger(2); }
Passenger jane = new Passenger(2, 3); purb
ilvi
ac
te Passenger(double perBagFee) {
this.perBagFee = perBagFee;
}
}
Demo
CalcEngine with Field Initializers and
Constructors
Initialization Blocks
public class Flight {
private int passengers, flightNumber, seats ;= 150;
Initialization blocks shared across all private char flightClass;
constructors
public Flight() {
- Executed as if the code were placed at seats = 150;
the start of each constructor passengers = 0;
public Flight(int flightNumber) {
this.flightNumber = flightNumber;
}
public Flight(char flightClass) {
this.flightClass = flightClass;
}
}
Initialization Blocks
public class Flight {
private int passengers, flightNumber, seats = 150;
Initialization blocks shared across all private char flightClass;
constructors private boolean[] isSeatAvailable;
public Flight() {
- Executed as if the code were placed at isSeatAvailable = new boolean[seats];
the start of each constructor for(int i = 0; i < seats; i++)
isSeatAvailable[i] = true;
- Enclose statements in brackets }
outside of any method or constructor
public Flight(int flightNumber)
{ this();
this.flightNumber = flightNumber;
}
public Flight(char flightClass)
{ this();
this.flightClass = flightClass;
}
}
Initialization Blocks
public class Flight {
private int passengers, flightNumber, seats = 150;
Initialization blocks shared across all private char flightClass;
constructors private boolean[] isSeatAvailable;
p{ublic Flight() { }
- Executed as if the code were placed at isSeatAvailable = new boolean[seats];
the start of each constructor for(int i = 0; i < seats; i++)
isSeatAvailable[i] = true;
- Enclose statements in brackets }
outside of any method or constructor
public Flight(int flightNumber)
{ this();
this.flightNumber = flightNumber;
}
public Flight(char flightClass)
{ this();
this.flightClass = flightClass;
}
}
Initialization and Construction Order
public class OverInitializedClass {
Field private int theField ;= 1;
Initialization public int getTheField() { return theField ; }
{
theField = 2;
}
Initialization
Block public OverInitializedClass() {
theField = 3;
OverInitializedClass c =
}
new OverInitialize dClass();
}
Constructor
System.out.println(c.getTheField();
1
3
2
Summary
Objects should be created in some useful state
Field initializers provide an initial value as part of the declaration
Every class has at least one constructor
- If no explicit constructor, Java provides one with no arguments
- You can provide multiple constructors with differing argument lists
One constructor can call another
- Call must be first line
Initialization blocks share code across constructors
Keep the initialization and construction order in mind
A Closer Look at Parameters
Jim Wilson
@hedgehogjim | blog.jwhh.com | jimw@jwhh.com
What to Expect in This Module
Parameter immutability
Constructor & method overloading
Variable number of parameters
Parameter Immutability
Parameters are passed by making a copy of the value
Known as passing “by-value”
Changes made to passed value
are not visible outside of method
Parameter Immutability: Primitive Types
int val1 = 10;
int val2 = 20;
val1 10 // print val1 & val2 val1 10
val2 20
swap(val1, val2);
val2 20 // print val1 & val2 val1 10
val2 20
i 20 void swap(int i, int j) {
int k = i;
i = j;
j 10 j = k;
k // print i & j i 20
10 } j 10
Parameter Immutability: Classes
Flight val1 = new Flight(10);
public class Flight {
int flightNumber;
// accessor & mutator elided for clarity
public Flight(int flightNumber) {
this.flightNumber = flightNumber;
}
void swap(Flight i, Flight j) {
// other members elided for clarity
}
}
Parameter Immutability: Classes
flightNumber
Flight val1 = new Flight(10);
10 Flight val2 = new Flight(20);
val1 // print val1 & val2 flight # val1 10
val2 20
flightNumber swap(val1, val2);
val2
20 // print val1 & val2 flight # val1 10
val2 20
i
void swap(Flight i, Flight j) {
Flight k = i;
i = j;
j
j = k;
k // print i & j flight # i 20
} j 10
Parameter Immutability
Parameters are passed by making a copy of the value
Known as passing “by-value”
Changes made to passed value Changes made to members of passed class
are not visible outside of method instances are visible outside of method
Parameter Immutability: Class Members
flightNumber
Flight val1 = new Flight(10);
1
20 Flight val2 = new Flight(20);
val1 // print val1 & val2 flight # val1 10
val2 20
flightNumber swapNumbers(val1, val2);
val2
10
2 // print val1 & val2 flight # val1 20
val2 10
i
void swapNumbers(Flight i, Flight j) {
int k = i.getFlightNumber();
j i.setFlightNumber(j.getFlightNumber());
j.setFlightNumber(k);
k i 20
10 // print i & j flight #
j 10
}
Overloading
A class may have multiple versions of its constructor or methods
Known as “overloading”
Each constructor and method must have a unique signature
Signature is made up of 3 parts
Number of parameters
Overloading
public class Passenger {
// fields & methods elided for clarity
public Passenger() {
public Passenger(int freeBags) {
this.freeBags = freeBags;
}
public Passenger(int freeBags, int checkedBags) {
this(freeBags);
this.checkedBags = checkedBags;
}
}
Overloading
A class may have multiple versions of its constructor or methods
Known as “overloading”
Each constructor and method must have a unique signature
Signature is made up of 3 parts
Number of parameters Type of each parameter
Overloading
public class Flight {
// fields & methods elided for clarity
public Flight() {
}
public Flight(int flightNumber)
{ this();
this.flightNumber = flightNumber;
}
public Flight(char flightClass)
{ this();
this.flightClass = flightClass;
}
}
Overloading
A class may have multiple versions of its constructor or methods
Known as “overloading”
Each constructor and method must have a unique signature
Signature is made up of 3 parts
Name Number of parameters Type of each parameter
Overloading
public class Flight {
// other members elided for clarity
int seats = 150, passengers;
int totalCheckedBags;
int maxCarryOns = seats * 2, totalCarryOns;
public void add1Passenger() {
if(hpasS
sent
gien
rgs()
<)seats)
passengers += 1;
else
handleTooMany();
}
private boolean hasSeating() {
return passengers < seats;
}
private boolean hasCarryOnSpace(int carryOns) {
return totalCarryOns + carryOns <= maxCarryOns;
}
}
Overloading
public class Flight {
// other members elided for clarity public void add1Passenger(Passenger p) { ... }
add1Passenger(p.getCheckedBags());
}
public void add1Passenger() { ... }
if(hasSeating())
passengers += 1; public void add1Passenger(int bags, int carryOns) { ... }
else if(hasSeating())&&{ hasCarryOnSpace(carryOns)) {
handleTooMany(); add1Passenger(bags());
} totalCarryOns += carryOns;
}
public void add1Passenger(int bags) { ... } }
if(hasSeating()) {
public void add1Passenger(Passenger p , int carryOns) {...}
add1Passenger();
add1Passenger(p.getCheckedBags(), carryOns);
totalCheckedBags += bags;
} }
}
}
}
Overloading
Flight f = new Flight(); Passenger
p1 = new Passenger(0,1); Passenger public class Flight {
p2 = new Passenger(0,2); // other members elided for clarity
f.add1Passenger(); public void add1Passenger() { ... }
f.add1Passenger(2);
public void add1Passenger(int bags) { ... }
f.add1Passenger(p1)
; public void add1Passenger(Passenger p) { ... }
short threeBags = 3; public void add1Passenger(int bags, int carryOns) { ... }
f.add1Passenger(threeBags, 2); public void add1Passenger(Passenger p , int carryOns) { ... }
f.add1Passenger(p2, 1); }
Demo
CalcEngine with Method Overloading
Variable Number of Parameters
public class Flight {
// other members elided for clarity
Flight f = new Flight(); public void addPassengers(Passenger[] list) {
Passenger janet = new Passenger(0,1); if(hasSeating(list.length)) {
passengers += list.length;
Passenger john = new Passenger(0,2);
for (Passenger passenger : list)
f.addPassengers( totalCheckedBags +=
new Passenger[] { janet, john}); passenger.getCheckedBags();
}
Passenger fred = new Passenger(0,2);
else
Passenger sarah = new Passenger(0,2);
handleTooMany();
Passenger susie = new Passenger(0,0);
}
f.addPassengers(
new Passenger[] {fred, sarah, susie}); private boolean hasSeating(int count) {
return passengers + count <= seats;
}
}
Variable Number of Parameters
public class Flight {
A method can be declared to accept a // other members elided for clarity
varying number of parameter values public void addPassengers(Paassenger.]
.. list) {
if(hasSeating(list.length)) {
- Place an ellipse after parameter type passengers += list.length;
- Can only be the last parameter for (Passenger passenger : list)
totalCheckedBags +=
- Method receives values as an array passenger.getCheckedBags();
}
else
handleTooMany();
}
private boolean hasSeating(int count) {
return passengers + count <= seats;
}
}
Variable Number of Parameters
public class Flight {
// other members elided for clarity
Flight f = new Flight(); public void addPassengers(Passenger... list) {
Passenger janet = new Passenger(0,1); if(hasSeating(list.length)) {
passengers += list.length;
Passenger john = new Passenger(0,2);
for (Passenger passenger : list)
f.addPassengers(janet, john); totalCheckedBags +=
new Passenger[] { janet, john}); passenger.getCheckedBags();
}
Passenger fred = new Passenger(0,2);
else
Passenger sarah = new Passenger(0,2);
handleTooMany();
Passenger susie = new Passenger(0,0);
}
f.addPassengers(fred, sarah, susie);
new Passenger[] {fred, sarah, susie}); private boolean hasSeating(int count) {
return passengers + count <= seats;
}
}
Summary
Parameters are immutable
- Changes made to passed value are not visible outside of method
- Changes made to members of passed class instances are visible outside of method
A class may have multiple versions of its constructor or methods
- Each must have a unique signature
- Signature includes name, number of parameters, type of each parameter
A method can be declared to accept varying number of parameter values
- Values received as an array
- Must be last parameter
Presenter
2016-05-20 11:18:24
--------------------------------------------
Welcome to the next module of the Pluralsight
Java Fundamentals course on the Java
language. In this module we discuss
class inheritance
Class Inheritance
Jim Wilson
@hedgehogjim | blog.jwhh.com | jimw@jwhh.com
What to Expect in This Module
Inheritance basics
Member hiding and overriding
The Object class
Object equality
The super keyword
Final and abstract
Inheritance and constructors
Class Inheritance
A class can be declared to inherit (a.k.a. derive) from another class
Use the “extends”keyword
Derived class has characteristics of base class
Can add specialization
Presenter
2016-05-20 11:18:25
--------------------------------------------
1000 CUBIC FEET of cargo space
Class Inheritance
public class CargoFlight extends Flight {
float maxCargoSpace = 1000.0f;
float usedCargoSpace;
public void add1Package(float h, float w, float d) {
double size = h * w * d;
if(hasCargoSpace(size))
CargoFlight cf = new CargoFlight(); usedCargoSpace += size;
cf.add1Package(1.0, 2.5, 3.0); else
handleNoSpace();
Passenger jane = new Passenger(0,2);
}
cf.add1Passenger(jane);
private boolean hasCargoSpace(float size) { return
usedCargoSpace + size <= maxCargoSpace;
}
private void handleNoSpace() {
public class Flight {
Syst em.out.println(“Not enough space”);
// other members elided for clarity
}
public void add1Pasenger(Passenger p) { ... }
} }
Class Inheritance
A class can be declared to inherit (a.k.a. derive) from another class
Use the “extends”keyword
Derived class has characteristics of base class
Can add specialization
Can be assigned to base
class typed references
Presenter
2016-05-20 11:18:26
--------------------------------------------
Really useful when passing as a method
Class Inheritance
parameter
public class CargoFlight extends Flight {
Flight f = new CargoFlight(); float maxCargoSpace = 1000.0f;
float usedCargoSpace;
Passenger jane = new Passenger(0,2);
f.add1Passenger(jane); public void add1Package(float h, float w, float d) {
double size = h * w * d;
f.add1Package(1.0, 2.5, 1.5); if(hasCargoSpace(size))
usedCargoSpace += size;
else
handleNoSpace();
Flight[] squadron = new Flight[5]; }
squadron[0] = new Flight(); private boolean hasCargoSpace(float size) { return
squadron[1] = new CargoFlight(); usedCargoSpace + size <= maxCargoSpace;
squadron[2] = new CargoFlight(); }
squadron[3] = new Flight(); private void handleNoSpace() {
squadron[4] = new CargoFlight(); System.out.println(“Not enough space”);
}
}
Class Inheritance
A class can be declared to inherit (a.k.a. derive) from another class
Use the “extends”keyword
Derived class has characteristics of base class
Can add specialization
Fields hide base class fields Can be assigned to base
with same name class typed references
Class Inheritance
public class CargoFlight extends Flight {
// other members elided for clarity
int seats = 12;
}
public class Flight {
Flight f1 = new Flight();
System.out.println(f1.seats); 150 // other members elided for clarity
int seats = 150;
CargoFlight cf = new CargoFlight;
System.out.println(cf.seats); 12 public void add1Passenger() {
if(hasSeating())
Flight f2 = new CargoFlight(); passengers += 1;
System.out.println(f2.seats); 150 else
handleTooMany();
f2.add1Passenger(); }
cf.add1Passenger(); private boolean hasSeating() {
return passengers < seats;
}
}
Class Inheritance
A class can be declared to inherit (a.k.a. derive) from another class
Use the “extends”keyword
Derived class has characteristics of base class
Can add specialization
Methods override base class
Fields hide base class fields Can be assigned to base
methods with same
with same name class typed references
signature
Presenter
2016-05-20 11:18:27
--------------------------------------------
Comment that the method can be simple
Class Inheritance
like this or as complex as necessary
@Overrode ANNOTATION
public class CargoFlight extends Flight {
// other members elided for clarity
@Override
int getSeats() { return 12; }
Flight f1 = new Flight(); }
public class Flight {
System.out.println(f1.getSeats());
150 // other members elided for clarity
CargoFlight cf = new CargoFlight; int getSeats() { return 150; }
System.out.println(cf.getSeats()); 12 public void add1Passenger() {
Flight f2 = new CargoFlight(); if(hasSeating())
passengers += 1;
System.out.println(f2.getSeats());
150 else
f2.add1Passenger(); handleTooMany();
cf.add1Passenger(); }
private boolean hasSeating() {
return passengers < getSeats();
}
}
Object Class
The Object class is the root of the Java class hierarchy
Every class has the characteristics of the Object class
Useful for declaring variables, fields
Defines a number of methods that
and parameters that can reference
are inherited by all objects
any class or array instance
Presenter
2016-05-20 11:18:28
--------------------------------------------
Comment that the method can be simple
Inheriting from Object
like this or as complex as necessary
@Overrode ANNOTATION
Every class inherits directly or indirectly from the Object class
Object
Flight Passenger
public class Flight {ex.t.e.nd}s Object public class Passenger { ... }
CargoFlight
public class CargoFlight extends Flight { ...
}
Presenter
2016-05-20 11:18:28
--------------------------------------------
Really useful when passing as a method
Object References
parameter
Object o = new
Passenger(); o = new
Flight[5];
Object[] stuff = new Object[3];
stuff[0] = new Flight(); o = new CargoFlight();
o.add1Package(1.0, 2.5, 3.0);
stuff[1] = new Passenger(0, 2);
stuff[2] = new CargoFlight();
Presenter
2016-05-20 11:18:28
--------------------------------------------
Really useful when passing as a method
Object References
parameter
CargoFlight Object o = new
o Passenger(); o = new
Flight[5];
o = new CargoFlight();
o.add1Package(1.0, 2.5, 3.0);
if(o instanceof CargoFlight) {
CargoFlight cf = (oC;argoFlight)
cf cf.add1Package(1.0, 2.5, 3.0);
}
Object Class Methods
Method Description
clone Create a new object instance that duplicates the current instance
hashCode Get a hash code for the current instance
getClass Return type information for the current instance
finalize Handle special resource cleanup scenarios
toString Return string of characters representing the current instance
equals Compare another object to the current instance for equality
Presenter
2016-05-20 11:18:29
--------------------------------------------
Because all classes inherit from the Ob jec
t
Equality
class … let’s use the Object class’
method, “equals”
…toIt bdeep
What does it mean en
equdals?
class Flight {
// other members elided for clarity
Flight f1 = new Flight(175); private int flightNumber;
Flight f2 = new Flight(175); private char flightClass;
if(f1 == f2) @Override
// do something public boolean equals (Object o)
{ if(!(o instanceof Flight))
if(f1.equals(f2)) return false;
// do something
Flight other = (Flight) o;
Passenger p = new Passenger(); return
if(f1.equals(p)) flightNumber == other.flightNumber &&
// do something
flightClass == other.flightClass;
}
}
Special Reference: super
Similar to this, super is an implicit
class Flight {
reference to the current object // other members elided for clarity
- super treats the object as if it is an private int flightNumber;
instance of its base class private char flightClass;
@Oviefr(rs
eiu
qdp
uee
arl.
s(o))
- Useful for accessing base class publircetbuoronletarnuee;quals (Object o) {
members that have been overridden if(!(o instanceof Flight))
return false;
Flight f1 = new Flight(175); Flight other = (Flight) o;
Flight f2 = f1; return
flightNumber == other.flightNumber &&
if(f1.equals(f2))
flightClass == other.flightClass;
// do something
}
}
Controlling Inheritance and Overriding
By default all classes can be extended
and derived classes have the option to use or override inherited methods
A class can change these defaults
Use final to prevent
inheriting and/or overriding
Using Final
public class CargoFlight extends Flight
// other members elided for clarity
public fvioniadl add1Package(float h, float w, float d) {
public fcilnaasls Passenger { double size = h * w * d;
// ... if(hasCargoSpace(size))
} usedCargoSpace += size;
else
handleNoSpace();
}
private boolean hasCargoSpace(float size) { return
usedCargoSpace + size <= maxCargoSpace;
}
private void handleNoSpace() {
System.out.println(“Not enough space”);
}
}
Controlling Inheritance and Overriding
By default all classes can be extended
and derived classes have the option to use or override inherited methods
A class can change these defaults
Use final to prevent Use abstract to require
inheriting and/or overriding inheriting and/or overriding
Presenter
2016-05-20 11:18:31
--------------------------------------------
Can call abstract method directly
Using Abstract
But can also be called by other *concret*
methods
public calbasstsraPcitlot { public class CargoOnlyPilot extends Pilot {
private Flight @Override
currentFlight; public void public boolean canAccept(Flight f) {
return f.getPassengers() == 0;
fly(Flight f) {
}
if(canAccept(f))
}
currentFlight = f;
else
handleCantAccept(); public class FullLicensePilot extends Pilot {
} @Override
public boolean canAccept(Flight f) {
public abstract boolean canAccept(Flight f) ;
return true;
private void handleCantAccept() { }
System.out.println(“Can’t accept”); }
}
}
Inheritance and Constructors
Constructors are not inherited
A base class constructor must always be called
By default, base class’ no-argument Can explicitly call a base class constructor
constructor is called using super followed by parameter list
Must be first line of constructor
Presenter
2016-05-20 11:18:32
--------------------------------------------
NO ARGUMENT constructor
Inheritance and Constructors
public class Flight {
public class CargoFlight extends Flight {
// other members elided for clarity
// other members elided for clarity
private int flightNumber;
float maxCargoSpace = 1000.0f;
public Flight() { }
public CargoFlight(int flightNumber) {
public Flight(int flightNumber) { super(flightNumber);
this.flightNumber = flightNumber; }
}
public CargoFlight(int flightNumber,
}
float maxCargoSpace) {
stuhpiesr(flightNumber);
this.maxCargoSpace = maxCargoSpace;
Flight f175 = new Flight(175); }
CargoFlight cf= new CargoFlight();
public CargoFlight() { }
CargoFlight cf294 = new CargoFlight(294);
public CargoFlight(float maxCargoSpace) {
CargoFlight cf85 = new CargoFlight(85, 2000.0f);
this.maxCargoSpace = maxCargoSpace;
CargoFlight cfBig = new CargoFlight(5000.0f); }
}
Demo
CalcEngine with Specialized Classes
Summary
Inheritance allows a new class to be defined with the characteristics of another
- Use the extend keyword
Derived class can override base class methods
- Optionally use @Override annotation
All classes derive from Object class either directly or indirectly
By default, object references are only equal when referencing the same instance
- Can override Object.equals to provide new behavior
super accesses current object as if instance of base class
final and abstract provide control over class inheritance and method overriding
Constructors are not inherited
String name = "Jim";
System.out.println("Hi " + name);
String greeting = "Hello";
greeting += " ";
greeting += "World";
String s1 = "I Love";
s1 += " Java";
String s2 = "I";
s2 += " Love
Java";
if(s1 == s2)
// do something
if(s1.equals(s2))
// do something
String s3 = s1.intern();
String s4 = s2.intern();
if(s3 == s4)
// do something
int iVal = 100; int i = 2, j = 3;
int result = i * j;
String sVal = String.valueOf(iVal);
System.out.println
(
i + " * " + j + " = " + result);
public class Flight {
int flightNumber;
char flightClass;
// other members elided for clarity
@Overrride Flight myFlight = new Flight(175);
public String toString() { System.out.println(
if(flightNumber > 0) "My flight is " + myFlight);
return "Flight #" + flightNumber;
else
return "Flight Class " + flightClass;
}
}
StringBuilder sb = new StringBuilder(40);
Flight myFlight = new Flight(175); String
- location = “Florida”;
• sb.append(“I flew to “);
sb.append(location);
- sb.append(“ on “);
- sb.append(myFlight);
int time = 9;
int pos = sb.length() - “ on “.length()
I flew to Florida on Flight #175
- myFlight.toString().length();
sb.insert(pos, “ at “);
sb.insert(pos + 4, time);
String message = sb.toString();
StringBuilder sb = new StringBuilder(40);
Flight myFlight = new Flight(175); String
- location = "Florida";
• sb.append("I flew to ");
sb.append(location);
- sb.append(" on ");
sb.append(myFlight);
int time = 9;
int pos = sb.length() - " on ".length()
I flew to Florida on Flight #175
- myFlight.toString().length();
StringBuilder sb = new StringBuilder(40);
Flight myFlight = new Flight(175); String
- location = "Florida";
• sb.append("I flew to ");
sb.append(location);
- sb.append(" on ");
- sb.append(myFlight);
int time = 9;
int pos = sb.length() - " on ".length()
I flew to Florida o
ant 9Flight #175
- myFlight.toString().length();
sb.insert(pos, " at ");
sb.insert(pos + 4, time);
String message = sb.toString();
Integer a = 100;
int b = a;
Integer c = b;
Integer a = 100;
int b = a;
Integer c = b;
Integer d = Integer.valueOf(100);
int e = d.intValue();
Integer f = Integer.valueOf(e);
Float g = Float.valueOf(18.125f);
float h = g.floatValue();
Integer a = 100;
int b = a;
Integer c = b;
String s = “87.44”;
Integer d = Integer.valueOf(100);
double s1 = Double.parseDouble(s);
int e = d.intValue();
Double s2 = Double.valueOf(s);
Integer f = Integer.valueOf(e);
Float g = Float.valueOf(18.125f);
float h = g.floatValue();
public class Flight {
Integer flightNumber;
Character flightClass;
// other members elided for clarity
Object[] stuff = new Object[3];
@Overrride
stuff[0] = new Flight(); stuff[1] public String toString() {
= new Passenger(0, 2); if(flightNumber != null)
stuff[2] = 100; return "Flight #" + flightNumber;
else if(flightClass != null)
return "Flight Class " + flightClass;
else
return "Flight identity not set ";
}
}
Integer i1000A = 10 * 10 * 10;
Integer i1000B = 100 * 10;
if(i1000A == i1000B)
// do something
if(i1000A.equals(i1000B))
// do something
Integer i8A = 4 * 2;
Integer i8B = 2 * 2 * 2;
if(i8A == i8B)
// do something
public class Passenger {
private final int freeBags;
// other members elided for clarity
public Passenger(int freeBags)
{ this.freeBags = freeBags;
}
}
public class Flight {
public class Passenger { static final int MAX_FAA_SEATS = 550;
private final int freeBags; private int seats;
// other members elided for clarity // other members elided for clarity
public void setSeats(int seats) {
public Passenger(int freeBags)
{ this.freeBags = freeBags; if(seats <= MAX_FAA_SEATS)
} this.seats = seats;
else
} // handle error
}
}
public class CrewMember {
private FlightCrewJob job;
// other members elided for clarity
public CrewMember(FlightCrewJob job) {
-
this.job = job;
- }
public void setJob(FlightCrewJob job) {
this.job = job;
public enum FlightCrewJob {
Pilot, }
CoPilot, }
CrewMember judy =
FlightAttendant, new CrewMember( FlightCrewJob.CoPilot);
AirMarshal // . . .
} Judy.setJob(FlightCrewJob.Pilot);
Exceptions and Error Handling
Jim Wilson
@hedgehogjim | blog.jwhh.com | jimw@jwhh.com
What to Expect in This Module
The role of exceptions
The try/catch/finally statement
Exceptions crossing method boundaries
Throwing exceptions
Custom exception types
Error Handling with Exceptions
Error handling needs to be implicit in application development
The traditional approach of checking error codes/flags is too intrusive
Exceptions provide a non-intrusive way to signal errors
try/catch/finally provides a structured way to handle exceptions
The try block contains the The catch block contains The finally block contains
“normal” code to execute the error handling code cleanup code if needed
Block executes to completion Block executes only if Runs in all cases
unless an exception is thrown matching exception is thrown following try or catch block
Error Handling with Exceptions
int i = 12;
int j = 2;
try { 0
int result = i / (j - 2);
System.out.println(result);
} catch(Exception e) {
System.out.println(
"Error: " + e.getMessage()); Error: / by zero
e.printStackTrace();
}
Error Handling with Exceptions
BufferedReader reader = null;
int total = 0;
try {
reader =
new BufferedReader(new FileReader("C:\\Numbers.txt")); C:\Numbers.txt
String line = null; 5
while ((line = reader.readLine()) != null) 12
6
total += Integer.valueOf(line);
4
System.out.println("Total: " + total);
} catch(Exception e) {
System.out.println(e.getMessage());
} finally
{ try {
if(reader != null)
reader.close();
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
Exception Class Hierarchy
Object
Throwable
Error Exception
LinkageError . .... . RuntimeException IOException . .. .. .
. .. . ..
Virtual machine related errors Checked exceptions
(Treated as unchecked)
NullPointerException . .... .
. ..
Unchecked exceptions
Typed Exceptions
Exceptions can be handled by type
Each exception type can Each catch is tested in order First assignable
have a separate catch block from top to bottom catch is selected
Start catch blocks with most specific exception types
Error Handling with Exceptions
BufferedReader reader = null;
int total = 0;
try {
reader =
new BufferedReader(new FileReader("C:\\Numbers.txt")); C:\Numbers.txt
String line = null; 5
while ((line = reader.readLine()) != null) 12
6
total += Integer.valueOf(line);
4
System.out.println("Total: " + total);
} catch(Exception e) {
System.out.println(e.getMessage());
} finally
{ try {
if(reader != null)
reader.close();
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
Error Handling with Exceptions
BufferedReader reader = null;
int total = 0;
try {
. . .
C:\Numbers.txt
} catch(Exception e) {
System.out.println(e.getMessage()); 5
12
6
4
} finally {
. . .
}
Error Handling with Exceptions
BufferedReader reader = null;
int total = 0;
try {
. . .
C:\Numbers.txt
} catch(Exception e) {
System.out.println(e.getMessage()); 5
} catch(NumberFormatException e) { 12
6
System.out.println(“Invalid value: “ +
e.getMessage()); 4
} finally {
. . .
}
Error Handling with Exceptions
BufferedReader reader = null;
int total = 0;
try {
. . .
Exception
} catch(NumberFormatException e) {
System.out.println(“Invalid value: “ +
e.getMessage());
} catch(FileNotFoundException e) { RuntimeException IOException
System.out.println(“Not found: “ +
e.getMessage());
... FileNotFoundException
} catch(IOException e) {
System.out.println(“Error interacting with file: “ +
e.getMessage());
NumberFormatException
} finally {
. . .
}
Exceptions and Methods
methodA
void methodA() {
. . .
try {
methodB();
} catch(. . .) {
. . . methodB
}
void methodB() {
} . . .
methodC();
methodC
} void methodC() {
. . .
methodD(); methodD
} void methodD() {
. . .
// Does something
// that throws an
// an exception
}
Exceptions and Methods
Exceptions propagate up the call stack
Can cross method boundaries
Exceptions are part of a method’s contract
Method is responsible for any checked exceptions that might occur
Catch the exception Document that the exception might occur
Use the throws clause
Exceptions and Methods
public class Flight {
int passengers;
// other members elided for clarity
public void addPassengers(String filename) throws IOException {
BufferedReader reader = null; C:\PassengerList.txt
try {
2 Wilson
reader = new BufferedReader(new FileReader(filename));
4 Rodriguez
String line = null;
while ((line = reader.readLine()) != null) { 7 Smith
String[] parts = line.split(" "); 4 Sharma
passengers += Integer.valueOf(parts[0]);
}
} finally {
if(reader != null)
reader.close();
}
}
}
Exceptions and Method Overriding
The throws clause of an overriding method must be compatible with
the throws clause of the overridden method
Can have the same Can have a derived
Can exclude exceptions
exception exception
public class CargoFlight extends Flight {
// other members elided for clarity
@Override throws IOException
public void addPassengers(String filename) {
// ... throws FileNotFoundException
}
}
Throwing Exceptions
Your code can throw exceptions
Use the throw keyword
Must create exception instance before throwing
Be sure to provide meaningful detail
When caused by another exception,
include originating exception
Most exception classes provide
a constructor that accepts a All exception classes support initCause method
String message or other detail
Many provide a constructor that accepts the
originating exception
Creating a Custom Exception Type
You can create your own custom exception types
In most cases better to use existing exception type
Normally inherit directly from Exception class
Makes them checked exceptions
Constructors are often their only members
Most required functionality is inherited
Constructor that accepts
Constructor that accepts
required detail and
required detail
originating exception
Demo
CalcEngine with Exceptions
Summary
Exceptions provide a non-intrusive way to signal errors
try/catch/finally provide a structured way to handle exceptions
Exceptions are caught by type
- Can have separate catch statement for differing exception types
- Catch from most specific type to least specific
Raise exceptions using throw
Methods must declare any unhandled checked exceptions using throws
Can create custom exception types
- Normally inherit from Exception
Working with Packages
Jim Wilson
@hedgehogjim | blog.jwhh.com | jimw@jwhh.com
What to Expect in This Module
What is a package?
Packages as a namespace
Importing packages
Limiting access to package contents
Distributing packages and archive files
What Is a Package?
A package is a group of related types
Create a namespace Provide an access boundary Act as a unit of distribution
Declaring Packages
Each source file identifies the associated package
Use package keyword
Package declaration must appear Applies to all types within
before any type declarations that source file
package xxxxxx ;
public class Flight {
// members elided for clarity
}
Packages Create a Namespace
Package name is part of the type name
Convention creates unique package
name
Follows reverse domain name structure
package com.pluralsight.travel ;
public class Flight {
// members elided for clarity
}
Packages Create a Namespace
Package name is part of the type name
Convention creates unique package Type name is qualified by package name
name
Follows reverse domain name structure
package com.pluralsight.travel ;
com.pluralsight.travel.Flight lax175 =
public class Flight {
// members elided for clarity new com.pluralsight.travel.Flight(175);
}
Determining a Type’s Package
Compiler needs to know each type’s package
Explicitly qualifying each type is impractical
Java offers several alternatives to explicitly qualifying types
Allows use of a type’s simple name in code
Types in the java.lang
package do not need to be
Types in current package do qualified Use type imports
not need to be qualified
Object, primitive wrapper classes,
String, StringBuilder, many more
Type Imports
Type imports guide compiler to map simple names to qualified names
Use import keyword
Single type import
Provides mapping for a single type
Single Type Import
package com.pluralsight.travel;
public class Flight {...}
package com.pluralsight.travel; import com.pluralsight.travel.Flight;
import com.xyzcompany.bar.Beer;
public class Passenger {...}
import com.pluralsight.travel.Passenger;
import com.xyzcompany.bar.Wine;
package com.xyzcompany.bar; Flight lax175 = new Flight(175);
Beer liteBeer = new Beer();
public class Beer {...}
Passenger jane = new Passenger();
package com.xyzcompany.bar; Wine merlot = new Wine();
public class Wine {...}
Type Imports
Type imports guide compiler to map simple names to qualified names
Use import keyword followed by qualified name
Single type import Import on demand
Provides mapping for a single type Provides mapping for all types in a
package
Import on Demand
package com.pluralsight.travel;
public class Flight {...}
package com.pluralsight.travel; import com.pluralsight.travel.Flight;
import com.xyzcompany.bar.Beer;
public class Passenger {...}
import com.pluralsight.travel.Passenger;
import com.xyzcompany.bar.Wine;
package com.xyzcompany.bar; Flight lax175 = new Flight(175);
Beer liteBeer = new Beer();
public class Beer {...}
Passenger jane = new Passenger();
package com.xyzcompany.bar; Wine merlot = new Wine();
public class Wine {...}
Import on Demand
package com.pluralsight.travel;
public class Flight {...}
package com.pluralsight.travel; import com.pluralsight.travel.*;
import com.xyzcompany.bar.*;
public class Passenger {...}
package com.xyzcompany.bar; Flight lax175 = new Flight(175);
Beer liteBeer = new Beer();
public class Beer {...}
Passenger jane = new Passenger();
package com.xyzcompany.bar; Wine merlot = new Wine();
public class Wine {...}
package com.xyzcompany.bar;
public class Flight {...}
Single Type Import
package com.pluralsight.travel;
public class Flight {...}
package com.pluralsight.travel; import com.pluralsight.travel.Flight;
import com.xyzcompany.bar.Beer;
public class Passenger {...}
import com.pluralsight.travel.Passenger;
import com.xyzcompany.bar.Wine;
package com.xyzcompany.bar; Flight lax175 = new Flight(175);
Beer liteBeer = new Beer();
public class Beer {...}
Passenger jane = new Passenger();
package com.xyzcompany.bar; Wine merlot = new Wine();
public class Wine {...}
package com.xyzcompany.bar;
public class Flight {...}
Type Imports
Type imports guide compiler to map simple names to qualified names
Use import keyword followed by qualified name
Single type import Import on demand
Provides mapping for a single type Provides mapping for all types in a
package
Preferred way to import types Use with caution
Exposes code to potential breakage
Most modern IDEs will add automatically
from changes in referenced packages
Limiting Access to Package Content
Packages can serve as an access boundary
Often referred to as package private
Useful for creating types and features to support functionality provided by the
package
Types and features are not meant to be used stand-alone
Can apply to a type Can apply to type members
Specific members of an otherwise accessible
Entire type is inaccessible outside of the package
type are inaccessible outside of the package
Access Modifiers
Modifier Visibility Usable Usable
on on
Types Members
Only within its own package
no access modifier Y Y
(a.k.a. package private)
public Everywhere Y Y
private Only within its own class N* Y
Only within its own class
protected N* Y
and subclasses
* As applies to top-level classes;
can be applied to nested-classes
Demo
Separating CalcEngine into Packages
Packages Provide a Unit of Distribution
Packages provide a predictable software structure
Simplifies distribution
Class files organized in hierarchical folders reflecting the package name
Each part of the package name is a separate folder
com
package com.pluralsight.travel;
public class Flight {...} pluralsight
travel
package com.pluralsight.travel;
public class Passenger {...}
Flight.class Passenger.class
Archive Files
Package folder structure can be placed into an archive file
Commonly known as a jar file
Places package folder structure into a single file
Supports compressing content
Optionally includes a manifest
Provides information regarding archive content
List of name-value pairs Commonly used to define startup class
Creating Archive Files
The JDK provides a utility for creating archive files
The jar command-line utility
Capability included with many other tools
Integrated development environments Build automation systems
Commonly known as IDEs Commonly known as build managers
Intellij IDEA Gradle
NetBeans Maven
Demo
Distributing CalcEngine as a Jar File
Summary
A package is a group of related types
- Package declaration must appear in source file before any type declarations
Type name qualified by package name
- Use import statements to map simple names to qualified names
Packages serve as an access boundary
Packages simplify distribution
- Types organized hierarchically according to the package name
- Archive files store package hierarchy in a single file
Creating Abstract Relationships with Interfaces
Jim Wilson
@hedgehogjim | blog.jwhh.com | jimw@jwhh.com
What to Expect in This Module
What an interface is
Implementing an interface
Implementing multiple interfaces
Declaring an interface
What Is an Interface?
An interface defines a contract
Provides no implementation
Classes implement interfaces
Expresses that the class conforms to the contract
Interfaces don’t limit
other aspects of
the class’
implementation
Implementing an Interface
public class Passenger implements Comparable {
// others members elided for clarity
java.lang.Comparable private int memberLevel; // 3(1st priority), 2, 1
private int memberDays;
Used for determining relative order public int compareTo(Object o) {
Passenger p = (Passenger) o;
One method: if(memberLevel > p.memberLevel)
compareTo return -1;
else if(memberLevel < p.memberLevel)
Receives item to compare
Return indicates current to return 1;
instance relative sequence else {
if(memberDays > p.memberDays)
Negative value: before return -1;
else if(memberDays < p.memberDays)
Positive value: after
return 1;
Zero value: equal else
return 0;
}
}
}
Implementing an Interface
public class Passenger implements Comparable {
// others members elided for clarity
Passenger bob = new Passenger(); private int memberLevel; // 3(1st priority), 2, 1
bob.setLevelAndDays(1, 180); private int memberDays;
Passenger jane = new Passenger(); public int compareTo(Object o) {
jane.setLevelAndDays(1, 90); Passenger p = (Passenger) o;
Passenger steve = new Passenger(); if(memberLevel > p.memberLevel)
return -1;
steve.setLevelAndDays(2, 180);
else if(memberLevel < p.memberLevel)
Passenger lisa = new Passenger();
return 1;
lisa.setLevelAndDays(3, 730); else {
if(memberDays > p.memberDays)
Passenger[] passengers =
return -1;
{bob, jane, steve, lisa};
else if(memberDays < p.memberDays)
Arrays.sort(passengers); return 1;
else
lisa steve bob jane }
return 0;
}
}
Implementing an Interface
public class Flight implements Comparable {
// others members elided for clarity
private int flightTime; // minutes past midnight
public int compareTo(Object o) {
Flight f = (Flight) o;
if(flightTime < f.flightTime)
return -1;
else if(flightTime > f.flightTime)
return 1;
else
return 0;
}
}
Implementing an Interface
public class Flight implements Comparable {
Flight lax045 = new Flight(); // others members elided for clarity
lax045.setFlightTime(45); private int flightTime; // minutes past midnight
Flight slc015 = new Flight();
slc015.setFlightTime(15); public int compareTo(Object o) {
Flight f = (Flight) o;
Flight nyc030 = new Flight(); return flightTime - f.flightTime;
nyc030.setFlightTime(30); }
}
Flight[] flights =
{lax045, slc015, nyc030};
Arrays.sort(flights);
slc015 nyc030 lax045
What Is an Interface?
An interface defines a contract
Provides no implementation
Classes implement interfaces
Expresses that the class conforms to the contract
Interfaces don’t limit Some interfaces require
other aspects of additional type information
the class’ Uses a concept known as generics
implementation
Implementing a Generic Interface
public class Flight implements Comparable <Flight> {
// others members elided for clarity
private int flightTime; // minutes past midnight
public interface Comparable<T> { public int compareTo(Flight f) {
Flight f = (Flight) o;
int compareTo(T o);
} return flightTime - f.flightTime;
}
}
Implementing a Generic Interface
public class Passenger implements Comparable <Passenger> {
// others members elided for clarity
private int memberLevel; // 3(1st priority), 2, 1
private int memberDays;
public int compareTo( Passenger p)
{ Passenger p = (Passenger) o;
if(memberLevel > p.memberLevel)
return -1;
else if(memberLevel < p.memberLevel)
return 1;
else {
if(memberDays > p.memberDays)
return -1;
else if(memberDays < p.memberDays)
return 1;
else
return 0;
}
}
}
What Is an Interface?
An interface defines a contract
Provides no implementation
Classes implement interfaces
Expresses that the class conforms to the contract
Interfaces don’t limit Some interfaces require Classes are free to
other aspects of additional type information implement multiple
the class’ Uses a concept known as generics interfaces
implementation
Implementing Multiple Interfaces
public class Flight
public class Person { implements Comparable<Flight> {
// other members elided for clarity // others members elided for clarity
private String name; private int flightTime;
} private CrewMember[] crew;
private Passenger[] roster;
public class CrewMember extends Person { public int compareTo(Flight f) {
// members elided for clarity Flight f = (Flight) o;
return flightTime - f.flightTime;
}
}
public class Passenger extends Person
implements Comparable<Passenger> {
// members elided for clarity
}
}
Implementing Multiple Interfaces
public class Flight
implements Comparable<Flight>, Iterable<Person> {
// others members elided for clarity
public interface Iterable<T> private int flightTime;
{ Iterator<T> iterator(); private CrewMember[] crew;
} private Passenger[] roster;
public int compareTo(Flight f) {
Flight f = (Flight) o;
public interface Iterator<T> { return flightTime - f.flightTime;
boolean hasNext(); }
T next();
public Iterator<Person> iterator() {
}
}
Implementing Multiple Interfaces
public class FlightIterator
implements Iterator<Person>
public class Flight
{ private CrewMember[] crew; implements Comparable<Flight>, Iterable<Person> {
private Passenger[] roster;
// others members elided for clarity
private int index = 0;
private int flightTime;
public FlightIterator(
private CrewMember[] crew;
CrewMember[] crew, Passenger[] roster) {
private Passenger[] roster;
this.crew = crew;
this.roster = roster; public int compareTo(Flight f) {
} Flight f = (Flight) o;
boolean hasNext() { return flightTime - f.flightTime;
return index < (crew.length + roster.length); }
}
public Person next() { public Iterator<Person> iterator() {
Person p = (index < crew.length) ? return new FlightIterator(crew, roster);
crew[index] : roster[index – crew.length]; }
index++;
return p; }
}
}
Implementing Multiple Interfaces
Flight lax045 = new Flight(45);
// Add crew members:
// Pilot Patty, CoPilot Karl, Marshal Mary
// Add Passengers:
// Bob, Jane, Steve, Lisa
for(Person p:lax045) Iterable<Person> laxIterable = lax045;
System.out.println(p.getName()); Iterator<Person> persons = laxIterable.iterator();
while(persons.hasNext()) {
Pilot Patty Person p = persons.next();
CoPilot Karl System.out.println(p.getName());
Marshal Mary }
Bob
Jane
Steve
Lisa
Declaring an Interface
Declaring an interface is similar to declaring a class
Use the interface keyword
Supports a subset of the features available to classes
Methods Constants Extending interfaces
Name, parameters, An interface can extend
Typed named values
and return type another interface
Implementing extended interface
Implicitly public Implicitly public, final, static
implies implementation of base
Demo
Dynamically Extending CalcEngine
1.0 + 2.0 = 3.0
add 1.0 2.0
Summary
An interface defines a contract
- Provides no implementation
- Can include methods and constants
Classes implement interfaces
- Classes are able to implement multiple interfaces
Interfaces are able to extend other interfaces
- Implementing an extended interface implicitly implements the base
Static Members, Nested Types,
and Anonymous Classes
Jim Wilson
@hedgehogjim | blog.jwhh.com | jimw@jwhh.com
What to Expect in This Module
Static members
Static initialization blocks
Nested types
Inner classes
Anonymous classes
Static Members
Static members are shared class-wide
Not associated with an individual instance
Declared using the static keyword
Accessible using the class name
Field Method
A value not associated with a specific instance Performs an action not tied to a specific instance
All instances access the same value Can access static fields only
Static Members
class Flight {
allPassengers
// other members elided for clarity
Flight.resetAllPassengers()
0 int passengers;
void add1Passenger() {
; System.out.println(
if(hasSeating()) {
0 Flight.getAllPassengers());
lax045 passengers += 1;
Flight lax045 = new Flight(); passengers allPassengers += 1;
lax045.add1Passenger(); } else
lax045.add1Passenger();
0 handleTooMany();
}
Flight slc015 = new Flight(); static int allPassengers;
slc015.add1Passenger(); static int getAllPassengers() {
slc015
return allPassengers;
passengers }
System.out.println(
0 static int resetAllPassengers() {
3 Flight.getAllPassengers());
allPassengers = 0;
}
}
Static Members
Static members are shared class-wide
Not associated with an individual instance
Declared using the static keyword
Accessible using the class name
Field Method
A value not associated with a specific instance Performs an action not tied to a specific instance
All instances access the same value Can access static fields only
Static import
Provides short hand for accessing static
members
Static Members
import static com.pluralsight.travel.Flight.resetAllPassengers;
import static com.pluralsight.travel.Flight.getAllPassengers;
Flight.resetAllPassengers();
System.out.println(
Flight.getAllPassengers());
Flight lax045 = new Flight();
lax045.add1Passenger();
lax045.add1Passenger();
Flight slc015 = new Flight();
slc015.add1Passenger();
System.out.println(
Flight.getAllPassengers());
Static Initialization Blocks
Static initialization blocks perform one-time type initialization
Executed before type’s first use
Statements enclosed in brackets outside of any method or
constructor
Precede with static keyword
Cannot access instance members Must handle all checked exceptions
Static Initialization Blocks
public class CrewManager {
private final static String FILENAME = "...";
private static CrewMember[] pool; CrewMember p =
public static CrewMember CrewManager.FindAvailable(FlightCrewJob.Pilot);
FindAvailable(FlightCrewJob job) {
CrewMember cm = null;
for(int i=0; i < pool.length; i++) {
if(pool[i] != null && pool[i].job == job) {
cm = pool[i]; Pilot,Patty
pool[i] = null; Pilot,Paul
break; CoPilot,Karl
CoPilot,Karen
}
} FlightAttendant,Fre
return cm; d
FlightAttendant,Phyllis
}
FlightAttendant,Frank
// other members temporarily elided
FlightAttendant,Fiona
} // class CrewManager AirMarshal,Ann
AirMarshal,Alan
Static Initialization Blocks
public class CrewManager { static {
BufferedReader reader =
private final static String FILENAME = "...";
null; try {
private static CrewMember[] pool; reader = new BufferedReader(. . .);
public static CrewMember String line = null;
FindAvailable(FlightCrewJob job) { int idx = 0;
CrewMember cm = null; pool = new CrewMember[10];
for(int i=0; i < pool.length; i++) { while ((line = reader.readLine()) != null) {
if(pool[i] != null && pool[i].job == job) { String[] parts = line.split(",");
cm = pool[i]; FlightCrewJob job =
pool[i] = null; FlightCrewJob.valueOf(parts[0]);
break; pool[idx] = new CrewMember(job);
} pool[idx].setName(parts[1]);
} idx++;
return cm; }
} } catch(IOException e) {
// handle error
}
}
} // class CrewManager
Static Initialization Blocks
CrewMember p =
CrewManager.FindAvailable(FlightCrewJob.Pilot);
CrewMember c =
CrewManager.FindAvailable(FlightCrewJob.CoPilot);
CrewMember a =
CrewManager.FindAvailable(FlightCrewJob.AirMarshal);
Nested Types
A nested type is a type declared within another type
Classes can be declared within Interfaces can be declared within
classes and interfaces classes and interfaces
Nested types are members of the enclosing type
Private members of the enclosing type are visible to the nested type
Nested types support all member access modifiers
public package private protected private
Nested Types
Nested types serve differing purposes
Structure and scoping
No relationship between
instances of nested and enclosing
type
Static classes nested within classes
All classes nested within interfaces
All nested interfaces
Nested Types
public class Passenger implements Comparable {
// others members elided for clarity
public static class RewardProgram {
private int memberLevel;
private int memberDays;
public int getLevel() { return level; }
public void setLevel(int level) { this.level = level; }
public int getMemberDays() { return memberDays; }
public void setMemberDays(int days) { this.memberDays = days; }
}
private RewardProgram rewardProgram = new RewardProgram();
public RewardProgram getRewardProgram() {
return rewardProgram;
}
}
Nested Types
Passenger steve = new Passenger();
steve.setName("Steve");
steve.getRewardProgram().setLevel(3);
steve.getRewardProgram().setMemberDays(180);
Passenger.RewardProgram platinum = new Passenger.RewardProgram();
platinum.setLevel(3);
if(steve.getRewardProgram().getLevel() == platinum.getLevel())
System.out.println("Steve is platinum");
Nested Types
public class Passenger implements Comparable {
// others members elided for clarity
public static class RewardProgram {
private int memberLevel;
private int memberDays;
public int getLevel() { return level; }
public void setLevel(int level) { this.level = level; }
public int getMemberDays() { return memberDays; }
public void setMemberDays(int days) { this.memberDays = days; }
}
private RewardProgram rewardProgram = new RewardProgram();
public RewardProgram getRewardProgram() {
return rewardProgram;
}
}
Nested Types
Nested types serve differing purposes
Structure and scoping Inner classes
No relationship between Each instance of the nested class is associated
instances of nested and enclosing with an instance of the enclosing class
type
Static classes nested within classes Non-static classes nested within classes
All classes nested within interfaces
All nested interfaces
Inner Classes
public class FlightIterator public class Flight
implements Iterator<Person> { implements Comparable<Flight>, Iterable<Person> {
private CrewMember[] crew; // others members elided for clarity
private Passenger[] roster; private CrewMember[] crew;
private int index = 0; private Passenger[] roster;
public FlightIterator( public Iterator<Person> iterator() {
return new FlightIterator( crew, roster );
CrewMember[] crew, Passenger[] roster) { }
this.crew = crew;
private class FlightIterator
this.roster = roster;
} implements Iterator<Person> {
public boolean hasNext() { private int index = 0;
return index < (crew.length + roster.length); public boolean hasNext() {
} return index < (crew.length + roster.length);
}
public Person next() {
public Person next() {
Person p = (index < crew.length) ? Person p = (index < crew.length) ?
crew[index] : roster[index – crew.length]; crew[index] : roster[index – crew.length];
index++; index++;
return p; return p;
}
} } }
}
Inner Classes
public class Flight
implements Comparable<Flight>, Iterable<Person> {
// others members elided for clarity
private CrewMember[] crew;
private Passenger[] roster;
public Iterator<Person> iterator() {
return new FlightIterator();
}
private class FlightIterator
implements Iterator<Person> {
private int index = 0;
public boolean hasNext() {
return index < (crew.length + roster.length);
Flight.this
Flight.this }
public Person next() {
Person p = (index < crew.length) ?
this crew[index] : roster[index – crew.length];
index++;
return p;
} }
}
Anonymous Classes
Anonymous classes are declared as part of their creation
Useful for simple interface implementations or class extensions
Anonymous classes are inner classes
Anonymous instance is associated with the containing class instance
Create as if you are constructing an instance of the interface or base class
Place opening & closing brackets after
Place implementation code within the brackets
the interface or base class
Anonymous Classes
public class Flight
implements Comparable<Flight>, Iterable<Person> {
// others members elided for clarity
private CrewMember[] crew;
private Passenger[] roster;
public Iterator<Person> iterator() {
return new FlightIterator();
}
private class FlightIterator
implements Iterator<Person> {
private int index = 0;
public boolean hasNext() {
return index < (crew.length + roster.length);
}
public Person next() {
Person p = (index < crew.length) ?
crew[index] : roster[index – crew.length];
index++;
return p;
} }
}
Anonymous Classes
public class Flight
implements Comparable<Flight>, Iterable<Person> {
// others members elided for clarity
private CrewMember[] crew;
private Passenger[] roster;
public Iterator<Person> iterator() {
return new Iterator<Person>() {
private int index = 0;
public boolean hasNext() {
return index < (crew.length + roster.length);
}
public Person next() {
Person p = (index < crew.length) ?
crew[index] : roster[index – crew.length];
index++;
return p;
}
}
}
}
Summary
Static methods and fields are shared class-wide
- Not associated with an individual instance
Static initialization blocks provide one-time type initialization
A nested type is a type declared within another type
- Can be used to provide structure and scoping
- Inner classes create an association between nested and enclosing instances
Anonymous classes are declared as part of their creation
- Useful for simple interface implementations and class extensions