OOP Java Learning Notes

Personal Learning Notes from Coursera Object Oriented Programming in Java, offered by UC San Diego.
Instructors: Mia Minners, Leo Porter, Christine Alvarado.
Author: Lisa Ding

Defining Classes and Creating Objects

  • A class is a type of data

  • An object is one such piece of data (with associated functionality)

  • Member variables: Data the objects need to store.

  • Methods: The things this class can do.

  • Constructor: Method to create a new object

  • “this” is the calling object

Overloading Methods

  • Default constructor
  • Parameter constructor

Overloading: Parameters must be different

  • Constructor
  • Method

Public vs Private

  • public means can access from any class
  • private means can access only within the class

Rule of thumb:

  • Make member variables private
  • Make methods either public or private (public for world use and private for helper methods)

Use Getters and Setters to access

public class SimpleLocation
{
    private double latitude;
    private double longitude;
    
    public double getLatitude(){
        return this.latitude;
    } // Getter
    public double setLatitude(double lat){
        this.latitude = lat;
}  //Setter

Getters and Setters give us more control

public void setLatitude (double lat)
{
    if (lat < 180 || lat > 180){
        System.out.println("Illegal value for latitude");
    }
    else{
        this.latitute = lat;
    }
}

Drawing Memory Models with Primitive Data

  • Variable declaration: int var1;
    draw a box and label it with the variable’s name

  • Variable assignment: var1 = 52;
    put the value of the right hand side (RHS) into the box for the variable on the left hand side(LHS)

Drawing Memory Models with Objects

Java has two categories of data: primitive data (e.g., number, character) and object data (programmer created types).

  • Primitive types(8):
    byte, short, int, long, float, double, boolean, char

     int var1 = 52;
    
  • Object types:
    Arrays and classes

      SimpleLocation ucsd = new SimpleLocation (32.9, -117.2);
    

Variable Scope

The scope of a variable is the area where it is defined to have a value.

  • Local variables are declared inside a method
  • Parameters behave like local variables
  • Member variables are declared outside any method

Introduction to GUIs using PApplet

GUI: Graphical User Interface
GUIs in Java - libraries: Swing/AWT/JavaFX/Processing

Processing has a class called PApplet

import processing.core.*;
public class MyPApplet extends PApplet {
    public void setup() {...}   //Executed once
    public void draw() {...}    //Loops often
}

Displaying Maps

Break down the problem into three stages:

  1. Setup map
  2. Read data for each country
  3. Display data for each country

1. Setup map

— Customising Maps

public class LifeExpectancy extends PApplet
{
    UnfoldingMap map;
    
    public void setup(){
        size(800, 600, OPENGL);
        map = new UnfoldingMap (this, 50, 50, 700, 500, new Google.GoogleMapProvider());
        MapUtils.createDefaultEventDispatcher(this, map);
    }
    
    public void draw(){
        map.draw();
    }
}

2. Read data for each country

— Reading and Storing Data

LifeExpectancyWorldBank.csv

Abstract Data Type(ADT): Map

Map: Keys —> Values
(Input —> Output)
(String: countryID —> Float: lifeExp)

Unique keys associated with values. Store pair of information/objects

public class LifeExpectancy extends PApplet
{
        UnfoldingMap map;
        Map<String, Float> lifeExpByCountry;

        public void setup(){
            …
            lifeExpByCountry = loadLifeExpectancyFromCSV(“data/lifeExpectancyWorldBank.csv”);  //Create Object of type Map
            …
        }
 }  

private Map <String, Float> 
        loadLifeExpectancyFromCSV(String fileName){ 
        //Create a helper method and keep it private

        Map<String, Float> lifeExpMap = new HashMap<String, Float> ( );
        // Constructor: Construct the map

        String [ ] rows = loadStrings(fileName);  
        //Read file
    
        for (String row : row)
    // For each ... in ...
         String [ ] columns = row.split(",");
         if (...) {
           float value = Float.parseFloat(columns[5]); // Convert string to float
            lifeExpMap.put(columns[4], value);
         }
     }

        return lifeExpMap;
}

3. Display data for each country

— Coloring Markers

  • Property and location (Class Feature)

  • Visual representation (Class Marker)

  • Marker Class: Marker interface for all markers to be drawn on to maps. A marker has at least one location, and properties. A marker can be drawn, selected, and tested if hit.

  • Feature Class: A feature stores one or more locations, its type, and additional data properties.

  • PointFeature Class: Stores a single location.

Abstract Data Type: List

`List<Feature> countries = new ArrayList<Feature>( );
Ordered list of things of type Feature
A collection of objects ordered in some way

  • List: Java “Interface”, Specifies behaviours, not implementation
  • ArrayList: Actual Java class, Implements List behaviours

List: Java “interface”; Specifies behaviours, not implementation, https://docs.oracle.com/javase/8/docs/api/java/util/List.html
ArrayList: Actual Java class; Implements List behaviours, http://docs.oracle.com/javase/8/docs/api

public class LifeExpectancy extends PApplet
{
        ...
        List<Feature> countries;
        List<Marker> countryMarkers;

        public void setup() {
        ...
        countries = GeoJSONReader.loadData(this,
data/countries.geo.json");
        countryMarkers = MapUtils.createSimpleMarker(countries);
        //1 Feature + 1 Marker per country
        //using helper methods provided in UnfoldingMaps

        map.addMarkers(countryMarkers);
        shadeCountries();
        ...
}

 private void shadeCountries() {
    for(Marker marker : countryMarkers){
        String countryId = marker.getId();
        
        if (lifeExpMap.containsKey(countryId)){
            float lifeExp = lifeExpMap.get(countryId);
            int colorLevel = (int) map (lifeExp, 40, 90, 10, 255);
            marker.setColor(color(255-colorLevel, 100, colorLevel));
        }
        else {
            marker.setColor(color(150, 150, 150));
        }
    }
 }

ArrayLists are like Arrays

  • set an element at an index:

Array version:
countryArray[0] = f, //feature
ArrayList:
countries.set(0, f);`

  • get the number of elements
    Array version:
    int len = countryArray.length;
    ArrayList:
    int len = countries.size( );

  • ArrayLists are resizable, but arrays are not.

      boolean add (E e)   //ArrayList will get bigger
      void add(int index, E element)
    
 public class LifeExpectancy extends PApplet
 {
     UnfoldingMap map;
     Map<String, Float> lifeExpMap;
     
     List <Feature> countries;
     List <Marker> countryMarkers;
     //Lists and ArrayLists declare what type they store: the countries store Features, and the countryMarkers store Markers.

     List <Feature> countries = new ArrayList<Feature>( );
     //Ordered list of things of type Feature
     List <Marker> countryMarkers = new ArrayList<Marker>( );
     ... // Code to add elements
 
     Feature f = countries.get(0);
     Marker m = countryMarkers.get(0);

Inheritance in Java

What did we want?

  • Keep common behaviour in one class
  • Spilt different behaviour into separate classes
  • Keep all of the objects in a single data structure

What is inherited?

  • public instance variables
  • public methods
  • private instance variables

Reference ———— Object
{Person p =} {new Person( );}
{Student s =} {new Student( );}

Person p = new Student( );
::A Student “is-a” Person::

Student s = new Person( ); ×

Person[ ] p = new Person[3]
p[0] = new Person( );
p[1] = new Student( );
p[2] = new Faculty( );
A Person array CAN store Student and Faculty objects

Visibility modifiers

Use appropriate visibility modifiers when writing classes.

  • {public}: can access from any class
  • {protected}: can access from same class, same package, any subclass
  • {package}: can access from same class, same package(Lose access by any subclass)
  • {private}: can access from same class

Rule of thumb 1: Make member variables private
(and methods either public or private)

Rule of thumb 2: Always use either public or private

Object Construction in Java

All classes inherit from Object class;
Java object construction occurs from the inside out.

'' Student s = new Student( );
new is an operator that allocates space;
this is passed to the constructor Student( );

Objects are created from the inside out

{Student} —> {Person} —> {Object}
(Subclass) —> (Superclass) —> (Indirect Superclass)

The compiler change the code:
{Your code} —> {Java Compiler} —> {Bytecode}
Your code: Human readable Java
Java Compiler: processes code and inserts new commands
Bytecode: runs on JVM

An example:

public class Person
{
      private String name;
}

The compiler gets the code, and will change the code in 3 steps:

Compiler Rules

Rule #1: No superclass? Compiler inserts: extends Object

public class Person extends Object
    //see how Person inherit from Object
{
    private String name;
}

Rule #2: No constructor? Java gives one for you.

public class Person extends Object  
{
    private String name;
    public Person( ){ 
       //Java gives you a default constructor with no arguments
    }
}

Rule #3:
1st Line must be:
this(args) //call other constructor in the same class
Or
super(args) //or call constructors from super class
Otherwise, Java inserts:
“super( ); ” //otherwise, call the default constructor of the super class

public class Person extends Object  
{
    private String name;
    public Person( ){ 
          super( );
    }
}

Exercise:

public class Student extends Person
 {
 }

—>

public class Student extends Person
 {
    public Student( )
    {
        super( );
    }
 }

The compiler makes this happen!

Initialising Variables in a Class Hierarchy

Use same-class and super class constructors in class creation

In the last chapter there remains a question: But how do we initialise name?

  • Code from last chapter:
public class Person extends Object  
{
    private String name;
    public Person( ){ 
          super( );
    }
}
  • Initialise name variable:
public class Person extends Object  
{
    private String name;
    public Person( String n ){ 
          super( );   // super( ) has to be the first line
          this.name = n;
    }
}

Another Example:

  • A False one:
public class Student extends Person
 {
    public Student( String n )
    {
        super( );
                this.name = n;  
                // False! name is a provate variable from the Person Class
                //How to initialise name without a public setter?
    }
 }

A Correct one:

 public class Student extends Person
 {
    public Student( String n )
    {
        super( n );
    }
 }

Let’s add a no-arg constructor:

 public class Student extends Person
 {
    public Student( String n )
    {
        super( n );
    }
 }
  
 public Student( ) {
     {
     super("Student");
     //Use a default value for name
     //No-arg constructor
     }
 }

A better way to do this:

 public class Student extends Person
 {
    public Student( String n )
    {
        super( n );
    }
 }
  
 public Student( ) {
     {
     this("Student");
     //Use our same class constructor
     }
 }

Method Overriding

  • Overloading: Same class has same method name with different parameters.
  • Overriding: Subclass has same method name with the same parameters as the superclass

Object class:
Modifier and Type: String;
Method and Description: toString( ):
toString( ): Returns a string representation of the object

public class Person{
    private String name;
    
     public String toString( ){
         return this.getName( );
     }
 }

//assume ctor
Person p = new Person("Tim");
System.out.println( p.toString( ) );  
//Calls Person's toString( ) instead of object's method because of overriding
// .toString( ) there is unnecessary beacuse println automatically calls toString( )
//So the code can be: System.out.println( p );

public class Student extends Person{
    private int studentID;

    public int getSID( ){
         return studentID;
     }
 public String toString( ){
     return this.getSID( ) + ": " + super.getName( );
     }
 }

//assume ctor
Person s = new Student ("Cara", 1234);
System.out.println( s );    
//Output: 1234: Cara  -- Because of Polymorphism!

Polymorphism: Introduction

Polymorphism: Superclass reference to subclass object

    Person s = new Student ("Cara", 1234);
 //assume appropriate ctors
 Person p [ ] = new Person [3];
 p [0] = new Person ("Tim");
 p[1] = new Student("Cara", 1234);
 p[2] = new Faculty("Mia", "ABCD")
 
 for(int i = 0; i < p.length; i++)
 {
     System.out.println( p[i] );    //toString( ) method depends on dynamic type
 }

Polymorphism: The appropriate method gets called.

Polymorphism: Compile Time vs. Runtime

Two steps:
Step 1: Compiler interprets code
Step 2: Runtime environment executes interpreted code

Compile Time Rules:

  1. Compiler ONLY knows reference type
  2. Can only look in reference type class for method
  3. Outputs a method signature

Run Time Rules

  1. Follow exact runtime type of object to find method
  2. Must match compile time method signature to appropriate method in actual object’s class

Polymorphism: Casting

Casting

  • Automatic type promotion (like int to double)

    • Superclass ref = new Subclass( ), widening
  • Explicit casting (like double to int)

    • Subclass ref = (Subclass) superRef; narrowing
Person s = new Student (“Cara”, 1234);
( (Student)s ).getSID( );

Runtime type check

instanceof: Provides runtime check of is-a relationship

if ( s instanceof Student)
{
    //only executes if s is-a Student at runtime
   ( (Student)s ).getSID( );
 }

Abstract Classes and Interfaces

Use the keyword abstract
Compare “inheritance of implementation” and “inheritance of interface”
Decide between Abstract Classes and Interfaces

  • Can make any class abstract with keyword ::abstract:::
public abstract class Person{
//Cannot create objects of this type
  • Class must be abstract if any methods are:
public abstract void monthlyStatement( ){
//Concrete subclasses must override this method

Abstract classes offer inheritance of both!

  • Implementation: instance variables and methods while define common behaviours
  • Interface: method signatures which define required behaviours

Event driven programming

  • Procedural: Code execution follows predictable sequence, based on control logic and program state.
 int[] vars = new int[7];
 for (int i=0; i<vars.length, i++)
 {
     vars[i] = i;
 }
  • Event driven
public void keyPressed()
{ ... }
public void mousePressed()
{ ... }

Searching and Sorting: From Code to Algorithms

LinearSearch Basic Algorithms

public static void findAirportCode(String toFind, Airport[] airports){
  int index = 0;
  while(index < airports.length){
    Airport curr = airports[index];
    if(toFind.equals(curr.getCity)){
      return curr.getCode;
    }
    index++;
  }
  return null;
}

Binary search algorithms: Cut the list in half, only search half the list

public static String findAirportCodeBS(String toFind, Airport[] airports){
    int low = 0;
    int high = airports.size() - 1;
    int mid;
    while (low < = high){
        mid = low + ((high-low)/2);
        int compare = toFind.compareTo(airports[mid].getCity());
        if (compare < 0){
            high = mid - 1;
        }
        else if (compare > 0){
            low = mid + 1;
        }
        else return airports[mid].getCode();
    }
return null;
}

Sorting Data

Selection Sort:

  • Find smallest element, swap it with element in location 0
  • Find next smallest element, swap it with element in location 1
  • etc

Basic Algorithm

  • For each position i from 0 to length-2
    • Find smallest element in “still unsorted”
      • Swap it with element in position i
public static void selectionSort (int[] vals){
    int indexMin;
    for(int i = 0; i < vals.length-1; i++){
        indexMin = i;
        for(int j = i+1, j<vals.length, j++){
            if(vals[j]<vals[indexMin]){
                indexMin = j;
            }
        }
        swap(vals, indexMin, i);
    }
}

Insertion Sort

Basic Algorithms

  • For each position i from 1 to length-1
    • Find correct location of i th element relative to first i-1
      • Swap successive pairs to get there
public static void insertionSort(int[] vals){
    int currInd;
    for(int pos = 1; pos < vals.length; pos ++){
        currInd = pos;
        while(currInd > 0 && vals[currInd] < vals[currInd-1])
        {
            swap(vals, currInd, currInd-1);
            currInd = currInd - 1;
        }
    }
}

Sorting Data

Java builtIn sort:

http://docs.oracle.com/javase/tutorial/collections/algorithms/

import java.util.*;

public class MyBuiltInSortingTesting{
    public static void main(String[] args){
        Random random = new Random();
        List<Integer> numsToSort = new ArrayList();

        for (int i = 0; i < 5; i++){
            numsToSort.add(random.nextInt(100));
        }
        Collections.sort(numsToSort);  //use build in merge sort
        System.out.println("New array after builtin sort:" + numsToSort.toString());
    }
}

Non integers?

public class Airport implements Comparable<Airport>{

    public int compareTo(Airport other){
        return (this.getCity()).compareTo(other.getCity());
    }
}

Personal Learning Notes from Coursera Object Oriented Programming in Java, offered by UC San Diego.
Instructors: Mia Minners, Leo Porter, Christine Alvarado.
Author: Lisa Ding

推荐阅读更多精彩内容