Object-Oriented-Programing Udacity 学习笔记

Lesson1- The World of Objects

good example to illustrate field and method

variable type:
*primitive variables : int
*object variables :Pokemon
object variables are made up of those primitive types
objects combine variables together to make your code meaningful + organized + easier to understand + simpler.

Object variables :
Method

*Field : also referred to as attributes or member variables. these fields can be 1.primitive types(usually) 2.objects themselves
for example: a book object may contain fields like title, author, and numberOfPages. Then a library object may contain a field named books that will store all book objects in an array.
Accessing fields: Accessing a field in an object is done using the dot modifier ‘.’ book.title -> set the fields book.numOfPages = 234
*Method: functions that belong to a particular object (we can create methods the same way we used to create functions)
Calling a method + set the method
java void setBookmark(int pageNum);//create a method called setBookmark book.setBookmark(12);//set a bookmark at page 12
*Summary of fields and methods: Fields and Methods together are what makes an object useful, fields store the object's data while methods perform actions to use or modify those data. Some object might have no fields while other objects might only have fields that as a way to organize storing data but not include any methods.

Classes:
Classes are symbolic representations of objects; classes describe the properties, fields, methods, and events that form objects in the same way that blueprints describe the items that form buildings. Just as a blueprint can be used to create multiple buildings, a single class can be used to create as many objects as necessary. Just as a blueprint defines which parts of a building are accessible to people who use the building, so too can classes control user access to object items through encapsulation. ---Microsoft Documentation

classes describe the structure of objects, while objects are usable instances of classes

classes describe the structure of objects, while objects are usable instances of classes. Each instance is an exact yet distinct copy of its class.
Classes and Objects
*emphasis: the Naming convention is different between the Class and Object

//Class is CamelCase while Object is camelCase
CLASS NAME: AnimalBehavior, Pokemon, BookStore
OBJECT NAME: australia, lordOfTheRings

The main method:
main() is the starting point of the program

public static void main(String[] args){
  //start my program here
}

Constructors:
*Constructors are special types of methods that are responsible for creating and initializing an object of that class

*Create a constructor:
constructor have the same name as the class itself and constructors don't have any return types

class Game{
    int score;
    //Default constructor
    Game(){
        score = 0;
    }
    //Constructor by starting score value also called Parameterized contructor
    Game(int startingScore){
        score  = startingScore;
    }
}

*Access a constructor:
normal methods: using "." operation to access. For example: Game.name
constructor method: using new keyword For example: Game tetris = new Game(); or Game darts = new Game(501);
if you do not initialize an object using the new keyword then its value will be set to null, null objects have no fields or methods, and will get a runtime error if trying to access a null object's field of calling its method.

Having multiple Constructor can help us customize when dealing with less common cases.

Self Reference:
*In order to disambiguate variable references, Sometimes we need to refer to an object within one of its methods or constructors, so use this.

this.name 表示class 里面的字段 name, this.name = name 中的name 表示传入的(String name)

check the difference
more uses about this, check here

Small Quiz: Contact Manager
Why is it a good idea to use a String variable to store a phone number than using an integer?
consider the 01, 001

'''java
//an example of java program: The Contacts Manager
class contact{
String friendName;
String phoneNumber;
String email;
}
class ContactManager{
int friendsNumber;
String [] contactFriends -> wrong //first create a contact class to store a few strings about your friend's contact information in 1 variable
Contact [] myFriends;
// Constructor:
ContactManager(){
this.friendsNumber = 0;
this.Contact = 500? -> wrong // using the new keyword to initialize any array(including the Contact array(which is a class)
this.myFrineds = new Contact[500];
}
//add a class methods addContact which will add a Contact object to the Contact array
void addContact(Contact contact){
Contact[friendsNumber] = contact; -> (wrong) ->myFriends[friendsNumber] = contact;
friendsNumber++;
}
Contact searchContact(String searchName){
for(int i = 0; i < friendsNumber; i++){
//pay attention to the method to compare the result
if(myFriends[i].name.equals(searchName)){
return myFriends[i];
}
}
return null;
}
}


![use " " instead of ' ' to store more than one character ](http://images2017.cnblogs.com/blog/1066857/201710/1066857-20171001063730544-767813281.png)

![Do not use class use object to call methods](http://images2017.cnblogs.com/blog/1066857/201710/1066857-20171001064545731-382007319.png)
check the solution [here](https://stackoverflow.com/questions/2694566/non-static-method-cannot-be-referenced-from-a-static-context) and [the reason behind the error](https://stackoverflow.com/questions/290884/what-is-the-reason-behind-non-static-method-cannot-be-referenced-from-a-static)

__Access modifiers__: 
*public / private
```java
public class Book{
   private String title;
   private String author;
   private boolean isBorrowed;
   public Book(String title, String author){
      this.title = title;
      this.author = author;
   }
   //setters method
   public void borrowBook(){
      isBorrowed = true;
   }
   public void returnBook(){
      isBorrowed = false;
   }
   //getters method
   public boolean isBookBorrowed(){
      return isBorrowed;
   }
}

Summary
⋅⋅
Always try to declare all fields as private
⋅⋅Create a constructor that accepts those private fields as inputs
⋅⋅
Create a public method that sets each private field, this way you will know when you are changing a field. These methods are called setters
⋅⋅Create a public method that returns each private field, so you can read the value without mistakingly changing it. These methods are called getters
⋅⋅
Set all your classes to public
⋅⋅Set all your fields to private
⋅⋅
Set any of your methods to public that are considered actions
⋅⋅*Set any of your methods to private that are considered helper methods

The private methods are usually known as helper methods since they can only be seen and called by the same class, they are usually there to organize your code and keep it simple and more readable. Any helper methods or methods that are only to be used internally should be set to private, all other methods should be public
nested classes

Lesson 2 User Interaction

Input Scanner
Using Java class Scanner:

  1. import the libraray
import java.util.Scanner;
  1. read data from a particular input
Scanner scanner = new Scanner(System.in); //the scanner will be reading from the System's input(basically the command line)
//this would continue to read whatever the user is typing until they hit "enter"
scanner.nextLine(); //calling the method nextLine() return a String that contains everything the user has typed in

__File Scanner__:
import java.io.File;
[Word Count Program](https://classroom.udacity.com/courses/ud283/lessons/297a7f29-2c0d-4e79-863b-d7c83b4026c1/concepts/076dcd1b-7951-4b0a-9750-55bcd8fed108)

__Use the terminal__:(skip)
[User Interaction](https://classroom.udacity.com/courses/ud283/lessons/297a7f29-2c0d-4e79-863b-d7c83b4026c1/concepts/cc82b82e-03ff-47e6-8627-d5d3812c608f)
__Exceptions__: (skip)
try  
catch or throw
syntax

__Inheritance__:
easy to understand and easy to extend and add more features 
*ENCAPSULATION: Each class is just like a capsule that contains everything it needs and nothing more
*POLYMORPHISM: Multiple shapes or forms
*INHERITANCE: Passing down traits or characteristics from a parent to their child  => extend their capabilities 


example: Bank Accounts
three different kinds of  share similar information -> parent 
![Three different type of account](http://images2017.cnblogs.com/blog/1066857/201710/1066857-20171003232547224-349076832.png)
![Create a class Account to involve all the attribute - cause extra waster](http://images2017.cnblogs.com/blog/1066857/201710/1066857-20171003232632615-938183367.png)
![Create different class for different Account Type - waste](http://images2017.cnblogs.com/blog/1066857/201710/1066857-20171003232601599-1716447292.png)
![Use Inheritance ](http://images2017.cnblogs.com/blog/1066857/201710/1066857-20171003232829021-2094814566.png)
- each class would have its own unique fields and methods while they all share the same basic attributes
![](http://images2017.cnblogs.com/blog/1066857/201710/1066857-20171003233152115-346976207.png)

```java 
class BankAccount{
    String acctNumber;
    double balance;
}
// use BankAccount as parent class and child class extend from it
class Checking extends BankAccount{
    double limit;
};

Polymorphism:
Treat objects as if they were types of their parents and still use all the functionality inside the child class itself


Bag&Items Example

Collaborate with different developer, you all focus on the same things but in the different attributes level
you focus on the weight, but the other developer focus on the different attributes of the item, such as the value, the color, the power, so they extend the class, but you can also use the parent class to write your own code
course link
Learn more about child class using parent constructor click here

Override:Child override methods that inherit from the parent
Combine with use of "Super": super keyword allow to re-use the parent method in the child class by using the "super" keyword

Interfaces:
Solve the problem of not able to inherit from multiple classes

Object's life-time

static

Collections

Arrays:
*initialize: java String[] ]names = new String[10]; Limitation not dynamic create wierd gap

ArrayLists:

ArrayList names = new ArrayList();
names.add("Arya");
names.add("Tim"); //use .add() method to add elements
names.remove("Tim") //use remove() method to remove elements

Some ArrayList Methods

//a shorthand for loops that don't require you to specify a loop counter variable 
//Basically reads: For each item in the list, print that item
for(String item : list){
    System.out.println(item);
}

Stack: First In Last Out
Stacks class methods

'''java
//Stack
Stack newsFeed = new Stack();
newsFeed.push("Morning news");
newsFeed.push("Afternoon news");
String breakingNews = (String) newsFeed.pop(); //Why there is a -> because the pop method actually return the type Object and not String, simply it has no idea what you've inserted and what type it is!
System.out.println(breakingNews);


__Queue__: First In First Out
![Queue and Deque methods](http://images2017.cnblogs.com/blog/1066857/201710/1066857-20171004115635021-585081954.png)
add() poll()

__Generics__:Generics enable classes to accept parameters when defining them
```java
ArrayList<String> listOfStrings = new ArrayList();
*For example: ArrayLists use Generics to allow you to specify the data type of the elements you're intending to add into that ArrayList.
*Generics also eliminate the need for casting 

List list = new ArrayList();
list.add("hello);
String s = (String) list.get(0);

List list = new ArrayList();
list.add("hello");
String s = list.get(0); // no cast (String)!!


__ArrayList methods: indexOf()__:Powerful method
```java 
//different kind of method to get the index
for(int i = 0; i < cities.size(); i++){
    if(cities.get(i).equals("Sydney")){
        return true;
    }
}

for(String city : cities){
    if(city.equals("Sydney")){
        return true;
    }
}

int indexOf(Object o) //This method returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element
cities.indexOf("Sydney");

The reason it is important to use the correct data structure for a variable or a collection is: Performance
A single program can be implemented in so many different ways, but only some will run smoothly and fast enough that users will want to continue using it.

HashMap: A HashMap is another type of collection that was introduced in Java to speed up the search process in an ArrayList.
HashMaps allow you to store a key for every item you want to add. This key has to be unique for the entire list, very much like the index of a typical array, except that this key can be any Object of any Type!

'''java
import java.util.HashMap;
public class Library{
HashMap<String, Book> allBooks;
} //create a collection of Books with a key of type String.
allBooks = nex HashMap<String, Book>(); //initialize this hash map
Book taleOfTwoCities = new Book();
allBooks.put("123", taleOfTwoCities); //add items to the HashMap
Book findBookByISBN(String isbn){
Book book = allBooks.get(isbn);
return book;
}//This code will use the String key to find the book instantly in the entire collection

Click [HERE](https://classroom.udacity.com/courses/ud283/lessons/d9b6371c-f3bb-4ebf-95dd-7c43d80b89f0/concepts/f8ed05b8-c273-4b62-9990-893b1b77da79) for review
原文地址:https://www.cnblogs.com/kong-xy/p/7613622.html