Lesson1- The World of Objects
variable type:
primitive variables : intobject variables :Pokemonobject 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 = 234Method: functions that belong to a particular object (we can create methods the same way we used to create functions) Calling a method + set the methodjava 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 Documentationclasses 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.
*emphasis: the Naming convention is different between the Class and Object//Class is CamelCase while Object is camelCaseCLASS NAME: AnimalBehavior, Pokemon, BookStoreOBJECT NAME: australia, lordOfTheRings
The main method:
main() is the starting point of the programpublic 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 typesclass 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) more uses about this, checkSmall Quiz: Contact Manager
Why is it a good idea to use a String variable to store a phone number than using an integer?'''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; } } ``` check the solution andAccess modifiers:
*public / privatepublic 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 methodsThe 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
Lesson 2 User Interaction
Input Scanner
Using Java class Scanner:- import the libraray
import java.util.Scanner;
- 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;Use the terminal:(skip)
Exceptions: (skip) try catch or throw syntaxInheritance:
easy to understand and easy to extend and add more featuresENCAPSULATION: Each class is just like a capsule that contains everything it needs and nothing morePOLYMORPHISM: Multiple shapes or forms *INHERITANCE: Passing down traits or characteristics from a parent to their child => extend their capabilitiesexample: Bank Accounts
three different kinds of share similar information -> parent- each class would have its own unique fields and methods while they all share the same basic attributes
class BankAccount{ String acctNumber; double balance;}// use BankAccount as parent class and child class extend from itclass 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 itselfBag&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 Learn more about child class using parent constructor clickOverride: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" keywordInterfaces:
Solve the problem of not able to inherit from multiple classesObject'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 elementsnames.remove("Tim") //use remove() method to remove elements
//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 itemfor(String item : list){ System.out.println(item);}
Stack: First In Last Out
'''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
add() poll()Generics:Generics enable classes to accept parameters when defining them
ArrayListlistOfStrings = 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 indexfor(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 elementcities.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 for review