Upload
ronald-whitehead
View
216
Download
0
Embed Size (px)
Citation preview
Java Tutorial
Object-Oriented Programming Concepts
• Object – a representation of some item
• state fields/members and should be encapsulated• behavior methods
• Class– an implementation of some object
• Interface– the contract between classes
• Inheritance– a way to share common aspects of objects
• Package– a way to organize a set things together.
Object-Oriented Programming Concepts
super class(common aspects)
subclass(which extends the super class to specialize)
extends
Language Basics• literals (constants)• variables
– instance, class, local, parameters– data types (primitive and objects)– assignments and comparisons
• operators (unary, binary, ternary)• expressions
– comparisons • a = "hello world"; b = "hello world";• (a == b) TRUE• a.equals(b) TRUE
• i1 = new Integer(1); i2 = new Integer(1);• (i1 == i2) FALSE• i1.equals(i2) TRUE
• statements• blocks• control flow
– if/then, switch, while, do/while, for, – branching - break, continue, return
Operator Precedence
Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ? :
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
public class Factorial{ /* The lowest value we can compute factorial for */ public final long FACTORIAL_LOW_VALUE = 0; // constant/literal
/* The highest value we can compute factorial for */ public final long FACTORIAL_HIGH_VALUE = 20; // constant/literal /* Error message for out of range values */ public final String INVALID_FACTORIAL_VALUE = "Error: factorial can only be computed for values between " + FACTORIAL_LOW_VALUE + " to " + FACTORIAL_HIGH_VALUE + ".";
/** * …. **/ public int factorial(int x) { int factorial = 1; // local variable to this method /* * By definition factorial can only be computed * for non-negative values, hence negative * values are not allowed. */ if((x < FACTORIAL_LOW_VALUE) || (x > FACTORIAL_HIGH_VALUE)) { throw new IllegalArgumentException(INVALID_FACTORIAL_VALUE); }/* if */ for(int i = 1; i <= x; ++i) { factorial *= i; }/* for */ return factorial; }/* public int factorial(...) */}/* public class Factorial */
Classes, Parameters, and Objects
• Classes– Constructors
• when they are and not provided– Override vs Overloading Methods
• override – replaces• overloading – augments
– don’t get in the habit of using:• static initialization blocks• unnamed initialization blocks
• Parameters– passed by value
• referenced and value type parameters• Objects
– declaration– instantiation– initialization
Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N