Java Programming FOR Android Development
Java Programming FOR Android Development
FOR
ANDROID DEVELOPMENT
1
Outline
• Getting Started
• Java: The Basics
• Java: Object–Oriented Programming
2
Getting Started
• (1)
Need to install Java Dev. Kit (JDK) to write Java
(Android) programs
– Don’t install Java Runtime Env. (JRE); JDK is different!
– Newer versions of JDK can cause issues with Android
• Can download JDK (free):
– Oracle’s JDK (http://java.oracle.com) free for dev. only;
payment for commercial use
• Alternatively, for macOS, Linux:
• macOS: Install Homebrew (http://brew.sh), then type
brew cask i n f o adoptopenjdk8 at command line
• Linux: Type sudo apt i n s t a l l d e f a u lt – j d k at
command line (Debian, Ubuntu)
3
Outline
• Getting Started
• Java: The Basics
• Java: Object–Oriented Programming
4
Java Programming
•
Language
Java: general-purpose
language: “write
code once, run
anywhere”
• The key: Java Virtual
Machine (JVM)
– Program code compiled
to JVM bytecode
– JVM bytecode
interpreted on JVM
5
Our First Java Program
p u b l i c class HelloWorld {
public s t a t i c void m a i n ( S t r i n g [ ] args)
{ System.out.println(“Hello
world!”);
}
}
8
Basic Data Types (2)
• Java’s primitive data types: [5]
13
Control Structures: Decision
• (2)
Example:
final double OLD_DROID = 5.0, f i n a l double NEW_DROID =
9.0; double myDroid = 8.1;
if (myDroid < OLD_DROID)
{
System.out.println(“Antique!”);
}
else i f (myDroid > NEW_DROID)
{
S y s t e m. o u t . p ri n t l n ( “Ve r y modern!”);
}
else
{
S y st e m. o u t . p r in t l n ( “Yo u r device: barely
supported.”);
}
Unlike the while loop, the do-while loop executes at least once so long as condition is true.
The while loop prints “aaaaaaaaaa” whereas the do-while loop prints “aaaaaaaaaaa” (11 as)
18
Control Structures: Iteration
• (3)
The for loop has the following structure:
f o r (<expression1>; <expression2>; <expression3>) {
. . .
}
• Semantics:
– <expression1> is loop initialization (run once)
– <expression2> is loop execution condition (checked every iteration)
– <expression3> is loop update (run every iteration)
• Example:
int i ;
f o r ( i = 0 ; i < 10; i + + )
{ System.out.println(“i = ” +
i);
}
System.out.println(“i = ” + i ) ;
25
Exception Handling
• (2) using the try-catch-finally structure:
We handle exceptions
try {
// Code t h a t could t r i g g e r an exception
}
catch (IndexOutOfBoundsException e ) { / / Or another
Exception
// Code t h a t “responds” t o
exception, e . g . , e . p r i n t S t a c k Tr a c e ( ) ;
}
finally {
// Code executes regardless o f
whether exception occurs
}
• There can be many catch blocks for different Exception s, but there is
only one t r y block and one (optional) f i n a l l y block. (See Section 7.4 in
[1] for the full hierarchy of Exception s)
• Exceptions always need to be caught and “reported”, especially in Android
26
Outline
• Getting Started
• Java: The Basics
• Java: Object–Oriented Programming
27
Objects and Classes (1)
• Classes serve as “blueprints” that describe the states and behaviors of objects,
which are actual “instances” of classes
• For example, a Vehicle class describes a motor vehicle’s blueprint:
– States: “on/off”, driver in seat, fuel in tank, speed, etc.
– Behaviors: startup, shutdown, drive “forward”, shift transmission, etc.
• There are many possible Vehicles, e.g., Honda Accord, Mack truck, etc.
These are instances of the Vehicle blueprint
• Many Vehicle states are specific to each Vehicle object, e.g., on/off, driver in
seat, fuel remaining. Other states are specific to the class of Vehicles, not any
particular Vehicle (e.g., keeping track of the “last” Vehicle ID # assigned).
These correspond to instance fields and static fields in a class.
• Notice: we can operate a vehicle without knowing its implementation “under
the hood”. Similarly, a class makes public instance methods by which objects
of this class can be manipulated. Other methods apply to the set of all
Vehicles (e.g., set min. fuel economy). These correspond to static methods in
31
a class
Objects and Classes (2)
p u b l i c class Vehicle {
/ / Instance f i e l d s (some omitted f o r b r e v i t y )
private boolean isOn = f a l s e ;
private boolean i sDriv erInSeat = f a l s e ;
p r i v a t e double fuelInTank = 10.0;
p r i v a t e double speed = 0 . 0 ;
/ / Static fi e l ds
private s t a t i c S t r i n g l a s t Vi n =
“4A4AP3AU*DE999998”;
/ / Instance methods (some omitted f o r
brevity)
public Ve h i c l e ( ) { … } / / Constructor
public void s t a r t U p ( ) { … }
public void s h u t O f f ( ) { … }
public void ge tIs D r i v er In Se at () { … }
/ / g e t t e r, s e t t e r methods
public void s et I s D ri v er I n S ea t ( ) { … }
p r i v a t e void manageMotor() { … }
/ / More p r i v a t e methods …
29
/ / S t a t i c methods
Objects and Classes (3)
• How to use the Vehicle class:
– First, create a new object via constructor Vehicl e() , e.g., Vehicle
myCar = new Ve h i c l e ( ) ;
– Change Vehicle states, e.g., s t a r t U p ( ) or s h u t O ff ( ) the Vehicle
– You can imagine other use cases
– Mark a new Vehicle ’s ID number (VIN) as “taken” by calling
Vehicle.setVin(…)
– Caveat: VINs more complex than this (simple) implementation
[7]
• Notes:
– Aliasing: If we set Vehicle myTruck = myCar, both myCar and
myTruck
“point” to the same variable. Better to perform “deep copy” of
myCar and store the copy in myTruck
– n u l l reference: refers to no object, cannot invoke methods on
null 30
–
Inheritance (1)
• Types of Vehicle s: Motorcycle , Car, Truck , etc. Types of Cars:
Sedan, Coupe, SUV. Types of Truck s: Pickup , Flatbed .
• Induces inheritance hierarchy
• Subclasses inherit fields/methods from superclasses.
• Subclasses can add new fields/methods, override those of
parent classes
• For example, Motorcycle ’s driveForward() method
differs from Truck’s driveForward() method
31
Inheritance (2)
• Inheritance denoted via extends keyword
p u b l i c class Vehicle { p u b l i c class Motorcycle
… extends Vehicle {
p u b l i c void driveForward …
(double speed) { p u b l i c void driveForward
/ / Base class (double speed) {
method / / Apply power…
} }
} }
32
Inheritance (3)
p u b l i c class Truck extends
Vehicle { p r i v a t e boolean
useAwd = true;
// . . .
public Truck(boolean
useAwd) {
this.useAwd =
useAwd; }
// . . .
public void
driveForward(double
speed)
{
if (useAwd) {
// Apply
power to 36
Polymorphism
• Suppose we create Vehicle s and invoke the driveForward() method:
Vehicle ve h icle = new Ve h i c l e ( ) ;
Vehicle motorcycle = new Mo t o rcycl e ();
Truck truck1 = new Tr u c k ( t r u e ) ; Vehicle
truck2 = new Tr u c k ( f a l s e ) ;
/ / Code here t o s t a r t vehicles…
ve h icle .d rive Fo rwa rd (5 . 0 );
motorcycle.driveForward( 1 0 . 0 ) ;
tru ck1 .drive Fo rward (15 .0);
truck2.d riveForwa rd (1 0.0 );
• For vehicle , Vehicle’s
driveForward () method is invoked
• For motorcycle , Motorcycle ’s
driveForward() method is invoked
• With truck1 and truck2 , Truck’s driveForward() function is invoked (with all-wheel
drive for truck1 , not for truck2 ).
• Dynamic method lookup: Java looks at objects’ actual types to find which method to
invoke
34
• Polymorphism: feature where objects of different subclasses are treated same way. (All
The Object Class
• Every class in Java is a subclass of Object
• Important methods in Object :
– t o S t r i n g ( ) : Converts Object to a S t r i n g
representation
– equals() : Compares Object s’ contents for equality
– hashCode() : Hashes the Object to a fixed-length
St ring , useful for data structures like HashMap, HashSet
• If you create your own class, you should override
t o S t r i n g ( ) and hashCode()
35
Interfaces
• Java interfaces abstractly specify methods to be implemented
• Intuition: decouple method definitions from implementations (clean design)
• Interfaces, implementations denoted by i n t e r f a c e , implements keywords
• Examples:
p u b l i c i n t e r f a c e Driveable {
p u b l i c void driveForward(double speed);
}
38