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
1066857-20170930084837044-740744879.png
*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
}

1066857-20171001052855231-575988212.png

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.
1066857-20171001060530262-1438144643.png
this.name 表示class 里面的字段 name, this.name = name 中的name 表示传入的(String name)

check the difference1066857-20171001060659856-730898120.png
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

Do not use class use object to call methods
check the solution here and the reason behind the error

Access modifiers:
*public / private

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
    ```java
    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

Use the terminal:(skip)
User Interaction
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
Create a class Account to involve all the attribute - cause extra waster
Create different class for different Account Type - waste
Use Inheritance

  • each class would have its own unique fields and methods while they all share the same basic attributes 1066857-20171003233152115-346976207.png
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
1066857-20171003235458161-168901262.png
1066857-20171003235435927-1477096555.png
1066857-20171003235504958-1885732090.png

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
add() poll()

Generics:Generics enable classes to accept parameters when defining them

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

//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 for review

转载于:https://www.cnblogs.com/kong-xy/p/7613622.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值