Android/GogoTraining/Introduction to Java 7 and Object-Oriented Programming

From Omnia
Jump to navigation Jump to search

.

Description

"This course provides you with an intensive, hands-on approach to learning the Java Programming Language. Presented as an evolving set of requirements, you will learn to use Java inputs and outputs, keywords, primate types, variables, packaging, and messaging while constructing a useful “real world” console application, create and use your own Java classes, arrays, Java Interfaces, generics, Object Orientation & Inheritance, as well as Java Templates, Collections and Exceptions."

Objectives

As a result of taking this course, you will be able to:

  • Create Java Programs that manage input, output, processing and errors
  • Use the most common Java keywords, operators and statements
  • Identify and apply “boxing” and “unboxing” in Java
  • Use arrays, generics, collections
  • Create objects that leverage object orientation
  • Create polymorphic frameworks in Java using Java Classes, inheritance, and Interfaces
  • Manage Java Objects using Arrays, Templates, and Collections

Outline

Module 00: Introduction to Java 7 and Object-Oriented Programming - Course Introduction

Module 01: What is Programming?

  • Java Inputs
  • Java Outputs
  • Java Processing
  • Java Tools and Types
  • Java Virtual Machine
  • Lab Exercise: Java Input and Output

Module 02: Java Variables, Packaging and Messaging

  • Java Packaging
  • System.out and System.error
  • Java Variables
  • Introduction to Classes
  • Lab Exercise: Reading Integral Input

Module 03: Lab Exercise Review: Reading Integral Input

Module 04: Basic Keywords and Types

  • Java Program Structure
  • Program Control Keywords
  • Keyword Statements
  • Control Keyword Usage
  • Lab Exercise: Using and IDE and Java Statements

Module 05: Java Primitive Types and Logical Operations

  • Control Statements: if, do, while
  • Strings
  • Java Primitive Minimum and Maximum Ranges
  • Lab Exercise: Class Console Loop

Module 06: Lab Exercise Review: Class Console Loop

Module 07: More Keywords and Classes

  • Package Importation
  • Common Classes
  • More Looping Key Words
  • “Boxing” and “Unboxing”
  • Lab Exercise: Using “for loop” iteration in Java

Module 08: Arrays and Operators

  • More Arrays
  • Java’s classic “for” keyword
  • Java’s new “for” keyword
  • Arithmetic Operators

Module 09: More Operators

  • Equality and Relational Operators
  • Conditional & Shortcut Operators
  • New Bit Shifting and Bit-Wise Operators
  • Self-Assignment & Shifting Operators
  • Precedence –v- Parentheses
  • Lab Exercise: Using Arrays

Module 10: Lab Exercise Review: Using Arrays

Module 11: Java Class Relationships Part 1

  • Basic Object Oriented Concepts
  • Default Class Parentage
  • Object Construction

Module 12: Java Class Relationships Part 2

  • Overriding Parent Methods
  • Creating Plain Old Java Objects (POJO)
  • Lab Exercise: Common Object Members and Operations

Module 13: More Keywords and Classes

  • Class Loaders, Members, Messaging and Information
  • The 3 Ps of Inheritance: Public, Private and Protective
  • POJO Example
  • Encapsulation
  • Switch Statement
  • Lab Exercise: Using POJO

Module 14: Lab Exercise Review: Using POJO

Module 15: Object Orientations Part 1

  • Java Constructors
  • Inheritance Order
  • Object Parentage
  • Construction Order

?Module 16: Object Orientations Part 2

  • Parameterized Construction
  • Constructor Reuse
  • Private Construction
  • Nested Classes

Module 17: Object Orientations Part 3

  • Object Oriented Concept Review
  • The 3 Pillars of Object Oriented Programming
  • Lab Exercise: Classes, Parents, Construction and Blocks

Module 18: Object Orientations Part 4

  • Diamond Inheritance
  • Java Interfaces
  • Abstract Classes

Module 19: Frameworks and Enumerations

  • Frameworks
  • Enumerations
  • Lab Exercise: POJO Inheritance and Enumeration

Module 20: Lab Exercise Review: POJO Inheritance and Enumeration

Module 21: Java Arrays

  • Processing Arrays
  • Passing Arrays
  • Array Problems

Module 22: Java Collections

  • Collections Beyond Arrays
  • Java Templates
  • Collection Families
  • Map, List and Dictionary
  • Lab Exercise: Using List, Map, Key and Dictionary

Module 23: Java Exceptions

  • Reusing Exceptions
  • “try”, “catch”, “throws”, “throw” and “finally”
  • Java Exception Hierarchy
  • Lab Exercise: Use Dates, Times and Exceptions

Module 24: Lab Exercise Review: Dates, Times and Exceptions

Requirements

00: Introduction to Java 7 and Object-Oriented Programming - Course Introduction

Everything is about class relationships and Object-Oriented Programming

Resources: student guide, exercise guide, lab files

01: What is Programming?

inputs, outputs, processing, tools, JVM

Java Virtual Machine (JVM) program

Java Runtime Environment (JRE)

Java Developer Toolkit (JDK)

Java program made up of classes, blocks, class members and class statements

Main:

class JavaOne {
  public static void main(String[] args) {
    System.out.println("Hello World");
  }
}

02: Java Variables, Packaging and Messaging

Popular IDEs:

Key-words:

  • case sensitive
  • control java processing
  • reserved - can't be used elsewhere

Variable - address that has changeable content

Java Packaging

  • qualification
  • name space

Static imports - don't have to specify in imports (eg. java.lang)

Ambiguity - when multiple classes of the same name are imported. To solve use fully qualified name.

Application Programming Interface (API)

Return type must match method definition

03: Lab Exercise Review: Reading Integral Input

umm... lab seems out of place

04: Basic Keywords and Types

Comments

// line comment
/* multi line
   comment */

POJO - Plain Old Java Object

Getters and Setters

flowchart diagram

  • modern: activity diagram
  • square - statements
  • diamond - choice
  • oval - start/end

05: Java Primitive Types and Logical Operations

Integer Ranges:

  • short = -32768 to 32767 | 2^15 | Short.MIN_VALUE Short.MAX_VALUE
  • int = -2147483648 to 2147483647 | 2^31 | Integer.MIN_VALUE Integer.MAX_VALUE
  • long = -9223372036854775808 to 9223372036854775807 | 2^63 | Long.MIN_VALUE Long.MAX_VALUE
  • double
  • float
  • character - two bytes for international languages
boolean myflag = true;

06: Lab Exercise Review: Class Console Loop

Moving code to separate classes to build your library

07: More Keywords and Classes

Simple Imports

  • Import into global name space
  • Use "Fully-Qualified" names in case of collision
  • Prefix with one level up

Static Imports

  • Works like auto-import (e.g. String)
import static java.lang.System.*;
...
out.println("hi");    // System.out...

Casting

All primitive types have a wrapper class.

Byte, Char, Short, Integer, Long, Double, Float, Boolean

Boxing - Wrapping a primitive in an Instance

Primitives & Wrapper Class

  • box - add primitive value to class
  • unbox - remove primitive value from class
  • wrap primitive types with a class
    • Integer, Double, Float, etc.
// boxing
int age = 39;
int MyIntance = new Integer(age)
// unboxing
int unboxed = MyInstance;

Casting:

System.out.println("char max = " + (int) Character.MAX_VALUE);

Syntactical Sugar

Mutable vs Immutable

String strA = "hello world";
stra.substring(0, pos)

String = collection of characters

  • java.lang.String
  • String are immutable

Substring and index:

String message = "Hello World";
if (message.indexOf("a") == -1) { ... }
String hi = message.substring(0, 5);
String letter = message.substring(0);

while:

while (true) {
 ...
 if (...) { continue; }
 if (...) { break; }
}
String str1 = "test";
char[] array = str1.toCharArray();

New for loop style:

for (char ch: array) { System.out.println(ch); }

Bytes:

String str = "hello";
char[] chars = str.toCharArray();
byte[] bytes = str.getBytes();
for (int ss = 0; ss < chars.length; ss++) {
  System.out.println("char:" + chars[ss] + " byte:" + bytes[ss]);
}
for (int ss = 0 ; ss < bytes.lenght; ss++) {
  System.out.println(" " + (char)bytes[ss]);
}

08: Arrays and Operators

		String[] result = null;
		result = "Hello World".split(" ");
		for(int i = 0; i < result.length; i++)
			out.println(i + "=" + result[i]);

My ArrayList test:

	public static void main(String[] args) {
		List<String> wordlist = new ArrayList<String>();
		String[] arrlist = "Hello World".split(" ");
		wordlist = Arrays.asList(arrlist);
		for(int i = 0; i < wordlist.size(); i++)
			out.println(i + "=" + wordlist.get(i));
		for(String word : wordlist)
			out.println(word);
	}

java - Convert String array to ArrayList - Stack Overflow - http://stackoverflow.com/questions/10530353/convert-string-array-to-arraylist

import java.util.Arrays;  
import java.util.List;  
import java.util.ArrayList;  
public class StringArrayTest  
{  
   public static void main(String[] args)  
   {  
      String[] words = {"ace", "boom", "crew", "dog", "eon"};  

      List<String> wordList = Arrays.asList(words);  

      for (String e : wordList)  
      {  
         System.out.println(e);  
      }  
   }  
}

String split:

String[] result = msg.split(" ");
for(String str : result) { out.println(str); }

Operators:

+ Unary Plus
- Unary Minus
++ Increment
-- Decrement
! Logical Complement
+ Additive (string concatenation)
- subtraction
* multiplication
/ division
% remainder (modulo)
++var vs --var

String concatenation

09: More Operators

== equal to
!= not equal to
> Greater than
>= Grater than or equal to
< less than
<= less than or equal to

Ternary:

boolean wantsData = false;
int calc = wantsData ? 22 : 42;
int calc = (wantsData) ? 22 : 42;  // parentheses add clarity?

Shortcut Operators:

if(bool1 && bool2) { ... } // ends at bool1 if false
if(boo1 || bool2) { ... } // ends at bool1 if true

Bit shifting & bitwise:

int bits = 0b111;
bits ^= Integer.MAX_VALUE; // XOR - SELF = shift left
- Unary compliment
<< signed shift left
>> signed shift right
>>> Unsigned shift right
& bitwise AND
^ bitwise exclusive OR (XOR)
| bitwise inclusive OR
int bits = 0b111;
System.out.println(Integer.toBinaryString(bits));

Assignment Operators:

=  +=  -=  *=  /=  %=
&=  ^=  |=  <<=  >>=

10: Lab Exercise Review: Using Arrays

Get comfortable with the IDE

shortcut-key: F3 - go to class definition

11: Java Class Relationships Part 1

Concepts:

  • Basic Object Oriented Concepts
  • Default Class Parentage
  • Object Construction

Naming Conventions for public interfaces

  • Start with alphabetic
  • Lower-case package name
  • Upper-case class name
  • Same-name revisions = numeric suffix
  • Underscores okay

All objects are related - Java.lang.Object (super parent class)

Static Imports

  • Instance NOT required
  • main activity started
package com.test;
import static com.test.helpers.reader.*;
public class testTwo {
  public static void main(String[] args) {
    out.println("Test");  // using static import
  }
}

Create class instance

public class Test { ... }
Test test = new Test();

Kenneth's Test:

test/Main.java:

package test;

import world.TestClass;

public class Main {

	public static void main(String[] args) {
		System.out.println("Instance Counter");
		TestClass testclass = new TestClass();
		System.out.println(testclass.InstanceCount());
		System.out.println(testclass.InstanceCount());

		System.out.println("Static Counter");
		System.out.println(TestClass.StaticCount());
		System.out.println(TestClass.StaticCount());
	}

}

world/TestClass.java:

package world;

public class TestClass {

	private int instanceCounter = 0;
	private static int staticCounter = 0;
	
	public int InstanceCount() {
		return this.instanceCounter++;
	}
	
	public static int StaticCount() {
		return staticCounter++;
	}
}

12: Java Class Relationships Part 2

Concepts:

  • Overriding Parent Methods
  • Creating Plain Old Java Objects (POJO)


POJO:

  • Should be Self Describing
  • Encapsulated Fields (data hiding)
    • Getters and Setters (data protection)
    • get = read
    • set = update
  • Design classes to be a "Noun/Verb" practices

CRUD operations

  • Create
  • Read
  • Update
  • Delete

java.lang.Object: (most related, and likely to be overridden)

  • .equals()
  • .toString()
  • .getHashcode()

Example of overriding .toString():

	@Override
	public String toString() {
		//return super.toString();
		return "I am a string";
	}

When overriding, should override .equals() and .getHashcode() at the same time.

NOTE: Operator overloading is not supported in Java, but is supported in C++.

Check if instance of:

if (obj instanceof SomeClass) { ... }

Casting:

SomeClass myclass = (SomeClass)obj;

"dot notation"

Correctly overriding an object:

public class UserId {
  int userId = 0;
  public UserId(int id) {
	  userId = id;
  }
  @Override
  public String toString() {
    return Integer.toString(userId);
  }
  @Override
  public int hashCode() {
    return toString().hashCode();
  }
  @Override
  public boolean equals(Object obj) {
    if(obj == null) return false;  // no-address test
    if(obj == this) return true;  // same-address test
    if(obj instanceof UserId) {
      UserId ref = (UserId)obj;  // same-class test
      return (this.userId == ref.userId);  // internal class id, if used
    }
    return false;
  }
}

test:

	public static void main(String[] args) {
		UserId uid1 = new UserId(1);
		UserId uid2 = new UserId(2);
		UserId uid3 = new UserId(1);
		System.out.println(uid1.toString());  // 1
		System.out.println(uid2.toString());  // 2
		System.out.println(uid3.toString());  // 1
		System.out.println(uid1.hashCode());  // 49
		System.out.println(uid2.hashCode());  // 50
		System.out.println(uid3.hashCode());  // 49
		System.out.println(uid1.equals(uid1));  // true
		System.out.println(uid1.equals(uid2));  // false
		System.out.println(uid1.equals(uid3));  // true
		
	}

@Override is Annotation to help compiler - not required, but highly recommended - ?see JSR250?

13: More Keywords and Classes

Concepts:

  • Class loaders, members, messaging and information
  • 3 Ps of Inheritance: public, private, protected
  • Inheritance - Re-use & Visibility


Class description (or class information)

Object.getClass()

Polymorphism - many faces, or may changes/morphs


"The 3 Ps" of Inheritance: Public, Private, Protected

  • Public - wherewhere
  • Private - self-only
  • Protected (default) - package only


Switch:

switch (option) {
  case '1':
    continue;
  case '2':
    break;
  default:
    // ...
}


Java Keyword Inventory

abstract	assert		boolean		break		byte		case
catch		chat		class				continue	default
double		do		else		enum		extends		false
final		finally		float		for				if
implements	import		instanceof	int		interface	long
native		new		null		package		private		protected
public		return		short		static		strictfp	super
swtich		synchronized	this		throw		throws		transient
true		try		void		volatile	while

14: Lab Exercise Review: Using POJO

Lab Example

15: Object Orientations Part 1

Concepts:

  • Java Constructors
  • Inheritance Order
  • Object Parentage
  • 'this' refers to SELF
  • 'super' refers to PARENT
public class MyClass extends MyParent {
  public MyClass() {
    super();  // call super class constructor
  }
}

16: Object Orientations Part 2

Parameterized Construction

public class MyClass extends MyParent {
  public MyClass(String msg) {
    super(msg);  // call super class constructor
  }
}

Note: Once we create a parameterized constructor, we loose the free default constructor.

public class MyClass extends MyParent {
  public MyClass() {
    this(42);  // call self constructor
  }
  public MyClass(String msg) {
    super(msg);  // call super class constructor
  }
}

Nesting Classes

  • Organize code
  • Associate classes
  • Govern creation dependences
  • Type types
    • Default nesting = parent only
    • Static nesting = use anywhere

Default and Static nesting:

public class Nesting {
  public Nesting() {
    new DefaultNest();
    new StaticNest();
  }
  public class DefaultNest {
    public DefaultNest() {}
  }
  public static class StaticNest {
    public StaticNest() {}
  }
  public static void main(String[] args) {
    // new DefaultNest();  // CAN NOT ACCESS!!
    new StaticNest();
    new Nesting();
  }
}

17: Object Orientations Part 3

3 Pillars of OOP:

  1. Encapsulation - Data Hiding
  2. Inheritance - hierarchical relationship tree
  3. Polymorphism - Morphing objects, Signature Rules (overloading/overriding), signature contracts

18: Object Orientations Part 4

Concepts:

  • Diamond Inheritance (multiple inheritance) - java doesn't support
  • Java Interfaces
  • Abstract Classes

Interfaces - As Java doesn't support multiple inheritance, instead is supports multiple interface contracts.

public interface Drawn {
  void drawObject();
}

public class Circle {
  public void drawCircle() { ... }
}

public class MyCicle extends Circle implements Drawn {
  public void drawCircle() {
    super.drawCircle()
  }
}

Abstract Class - does not provide implementations for all its methods. A parent class that *has* to be overridden.

public abstract class aCircle {
  abstract void drawCircle();
}

public class MyCirlce extends aCircle {
  @Override
  void drawCirlce() { ... }
}

Concrete Class - A derived class that implements all the missing functionality is called a concrete class

Getting class details:

for (Object ref : array) { ... }
String.class.getName()
obj.getClass().getName()

19: Frameworks and Enumerations

Frameworks - is a set of classes and interfaces that implement commonly reusable collection data structures. Although referred to as a framework, it works in a manner of a library.

---


Enumeration gives names to values (name tags)

enum MenuOptions {
  mo_None, mo_Create, mo_Delete, ..., mo_Quit,
};

MenuOptions option = MenuOption.mo_None;

switch (option) {
  case mo_Create:
    ...
}

Enum with constructors:

public enum MenuOptions {
  mo_None("Mani Menu"),
  mo_Create("Create Record"),
  ...
  mo_Quit("End");
  public string message = "";
  private MenuOptions(String message) {
    this.message = message;
  }
};

20: Lab Exercise Review: POJO Inheritance and Enumeration

lab exercise

21: Java Arrays

22: Java Collections

23: Java Exceptions

24: Lab Exercise Review: Dates, Times and Exceptions