Java基础Java学习笔记Java学习笔记

OOP Java Learning Notes

2016-05-22  本文已影响82人  LisaDing

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

Overloading Methods

Overloading: Parameters must be different

Public vs Private

Rule of thumb:

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

Drawing Memory Models with Objects

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

Variable Scope

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

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

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, 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

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

 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?

What is inherited?

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.

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?

public class Person extends Object  
{
    private String name;
    public Person( ){ 
          super( );
    }
}
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:

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

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

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

public abstract class Person{
//Cannot create objects of this type
public abstract void monthlyStatement( ){
//Concrete subclasses must override this method

Abstract classes offer inheritance of both!

Event driven programming

 int[] vars = new int[7];
 for (int i=0; i<vars.length, i++)
 {
     vars[i] = i;
 }
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:

Basic Algorithm

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

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

上一篇 下一篇

猜你喜欢

热点阅读