User:Muffingg/OOD

General Java Notes
Animal dog = new Dog;
 * A class is something you can use to create objects from
 * Java package is nothing more than a simple folder containing bits of java files
 * Packages are saved as com.fdm.package in order to make it unique globally
 * Member variables are defined outside the methods in a class, so they can be accessed for any method
 * Local variables are defined within a method only and do no longer exist after a method has ended
 * Objects (ferrari) only contain addresses in the memory to point to a (Car) object
 * Every single class inherits from the Object class
 * Object is an instance of a Class (Class is a template)
 * this refers to the variables in the class (global variables)
 * Upcasting - is the process of turning the child into the parent, e.g.:
 * Downcasting - is the process of turning the parent object into a child object, e.g.:
 * For each loop does not work well if you need to change the contents
 * Remember where all the exception classes are for the exam
 * A method can have only up to 1 return value
 * Pass by Value or Pass by Reference is coming up in the test for sure
 * Exam will have 20 MCQ and 5 short answer questions


 * // is for single line comments
 * /* Multiline comments are like this */

=Week 1=

Java is a strongly, manifestly, statically typed Programming Language


 * Strongly - data types are fixed and not flexible
 * Manifestly - every variable has to be declared with its data type
 * Statically - each variable can be used without being defined

2 types of programming languages
 * Compiled:
 * you run it through with a compiler, which stores it in a separate (compiled) file containing the machine code
 * faster
 * you're able to find problems before running it (unlike Unix)
 * compiled file will only be created if there are no errors, so there is error checking happening as you are running the file


 * Interpreted programming languages (e.g. Unix):
 * each line will be converted as it runs into machine code (the code that is readable to the computer)

JVM

 * JVM is the Java Virtual Machine
 * Java machine code runs on the JVM of the particular Operating System (Win7 / Unix / etc.)

Data Types

 * There are 8 primitive data types in Java
 * byte - this holds an integer, but only an integer (-128 to 127)
 * boolean - true/false
 * char - one character
 * float - 32bit decimal numbers (default value is 0.0f)
 * long - goes way above 2bn (rarely used)
 * short - this holds an integer (+32000 to -32000)
 * int - default integer type (+2bn to -2bn)

Loops
while (count < numberOfBooks){ total += basket[count].getPrice; count++; }
 * While Loop:

for (Book book : basket){ total += book.getPrice; }
 * For each Loop:

String and StringBuilder

 * String objects are immutable (cannot be changed and changing means creating a new object)
 * Arrays are also immutable
 * StringBuilder and StringBuffer should be used instead of String if you want to make lots of changes
 * In order to make lots of changes to a String, put it into a StringBuilder
 * StringBuffer is a thread-safe method (only one process could make changes to it at a time)
 * StringBuilder is thread-unsafe (it's possible for 2 processes to make changes to a StringBuffer)
 * Other than that they are both the same

Arrays and ArrayList
ArrayList basket = new ArrayList; //Generic ArrayList (of any type of object) ArrayList basket = new ArrayList; //ArrayList of type book only
 * ArrayList is created as follows:

UML Class Diagram

 * - is for private
 * + is for public
 * # is for protected
 * add <<: String>> after the method for return type (even for void)

Abstract Class
public abstract void accelerate;
 * Shown in italics in a Class diagram
 * An abstract class is purely for inheritance purposes
 * Can only extend from ONE class
 * Abstract Classes can't be instantiated
 * Child classes MUST implement parent class' methods
 * Abstract method is defined as (e.g.):
 * Generalisation (filled line with solid arrow heads)

Interface

 * Shown with < > above the interface name in a Class diagram
 * Similar to Abstract Class, but can support multiple inheritance
 * Can only have abstract methods
 * Child classes must implement all methods from the interface unless it's an abstract class
 * Realisation (dashed arrow with solid arrow heads)

Dependency Connectors
Dependency
 * Used in a method Teller 'uses a' Account object in a method

Association
 * Database 'has a' connection object as variable

Aggregation
 * Exchange 'has many' Broker objects Broker can exist outside the Exchange

Composition
 * StockIndex 'requires' Exchange, Exchange 'has many' StockIndex's

Polymorphism

 * Sub Class = Car
 * Parent Class = Vehicle
 * Overriding
 * This happens when a class extends from another class. The subclass' method will be the one that is run, not the parent class'
 * The parent class' method is therefore overridden by the subclass' method
 * Overloading
 * When there are 2 methods with the same name in a class but taking an argument, then the argument method will overload the non-argument method

Maven

 * Maven imports external tools that we may be needing (from Internet into Eclipse)

TDD (Test Driven Development)

 * Every test will be a void name


 * 5 Rules of JUnit Tests
 * Simple - no loops or if statements, only one scenario
 * Focused - should focus on one particular method (or one aspect of a method)
 * Easy to read
 * Independent - each test should be independent of all the other tests
 * Flexible


 * 5 Steps of testing
 * Write the test
 * Compile the test
 * Watch the test fail
 * Write minimal code to pass the test
 * Refactor + Generalise


 * AAA
 * Arrange - create the objects we're going to be using in the test
 * Act -
 * Assert

Exceptions

 * Exceptions are generally not the fault of the programmer
 * Throwable
 * Error
 * VirtualMachineError
 * Exception
 * RuntimeException
 * (Checked Exception)


 * CheckedExceptions are the other exceptions (IOExceptions, ClassNotFoundExceptions, Custom Checked Exceptions <- user defined ones)


 * RuntimeExceptions are unchecked exceptions, we shouldn't be handling these
 * NullPointerException is when a reference exists and the object does not
 * or when there is a null


 * Create your own exception every time you want to catch a specific exception and not a runtime exception

Memory Handling
Stack
 * contains:
 * object references
 * primitives
 * well ordered

Heap
 * contains:
 * objects
 * in random order

Two different ways in which a programming language passes objects
 * Pass by Value
 * Pass by Reference


 * Java is a pass by value programming language

=Week 2=

General Notes

 * A good practice is to test the size of a collection as part of TDD
 * Same with removing something to the collection
 * static can be used to keep track to how many accounts there are

Collections

 * A list can have duplicates and order
 * A set has no duplicates and no order
 * In a HashSet, adding a duplicate will simply overwrite the previous object
 * Only difference between Vector and ArrayList is that Vector is thread-safe (allows access at the same time by 2 different people)
 * Difference between TreeMap and HashMap is that a TreeMap arranges the keys in some sort of orders, while HashMap creates hashes to each key and orders according to that

Map

 * A collection is a way of storing data of the same type#


 * For HashMaps, you use put in order to put something in
 * Only a duplicate key would cause a problem and overwrite the existing value for that particular key
 * There are 3 ways to display everything that is in a map:
 * KeySet
 * EntrySet
 * Values
 * Maps are sorted by hash codes
 * Map DOES NOT extend from Collections but it is part of the Collections hierarchy

LinkedList

 * Similar to ArrayList
 * Each item has a reference to the next item
 * Adding one item to LinkedList creates an item with a pointer to the next item (nowhere) and to a previous item (nowhere)
 * Adding a second item creates the reference of the first item to this second item
 * Items can be added at any specific point (before a specific item, even before the first item)
 * It is faster to sort it because it uses O(n log n) instead of O(n^2), which would take far longer to sort as it is a square graph instead of a log graph

Priority Queue

 * First in first out

Stack

 * Last in first out
 * It's like a plate stack, you put new plates in at the top, and take them from the top
 * Push and pop to add and remove

Comparator and Comparable

 * Car implements Comparable in order to make it comparable
 * -1 means leave them in the same order
 * 1 means switch them around
 * 0 means they're the same size, so don't matter

Collections.sort(carsList, carComparator);
 * Collections.sort can be overloaded by having 2 arguments e.g.

Mockito

 * JUnit
 * is for testing methods with return types
 * tests data
 * Mockito
 * is for testing methods with void returns
 * it can test classes independently
 * tests behaviour

import static org.mockito.Mockito.*; import org.mockito.Mock; Wheel mockWheel = mock(Wheel.class); verify(mockWheel, times(1)).spin; when(mockWheel.getSize).thenReturn(100);
 * Mock objects are fake objects if one of the two classes isn't finished
 * e.g. if the Wheel Class is not finished but the Car class is, the Car class can be tested with a mock Wheel class
 * Need the following imports in order to use Mockito:
 * Mock objects are created like this:
 * Verify works as follows:
 * Stubbing example:

Input / Output

 * InputStream and OutputStream work with bytes
 * Reader and Writer work with characters

=Week 3=

Log4J

 * Logging levels are as follows:
 * Fatal, Error, Warning, Info, Debug, Trace
 * Turning off log4j happens by going to the log4j.properties file and turning 'ALL' to 'OFF'
 * 'ERROR' would mean error or higher

SOLID Principles
( Aside: Dependency Injection )
 * Single Responsibility
 * Your class should do one thing (related things) only and do it well
 * Bank account should only be about bank account alone
 * Open/Close
 * Open for extensions, closed for modifications
 * Liskov Substitution
 * Parent class reference can be replaced by a child reference (e.g. Vehicle and Car)
 * Interface Segregation
 * Breaking down a big interface into multiple smaller interfaces
 * Dependency Inversion
 * Use more general types instead of more specific ones
 * E.g. have a general method that deals with all shares rather than a method for each type of share


 * Code being highly flexible
 * Program easily extendable / scalable
 * Loosely coupled (easily replacable and not so rigid)

Access Modifiers

 * Final
 * Final class cannot be extended
 * Final method cannot be overridden
 * Final variables cannot be changed
 * Static
 * Static method can be called by className.methodName (without instantiating it)
 * Static variables belong to all objects and also don't need to be instantiated
 * Public
 * Public class is visible to all packages
 * Public variables are accessible and can be changed from any class
 * Public methods can be called from outside the class
 * Private
 * Private variables can only be accessed from the class itself
 * Private methods can only be accessed from within the class
 * Protected
 * Protected variables are visible to itself and any subclasses (classes extending from it)
 * Default
 * Default class is only visible within the same package (can't even be imported)
 * Default variables are visible to the package only
 * Default methods are visible to the package only

Threading

 * Need to either extend Thread or implement Runnable
 * The states of a thread are as follows:
 * New -> Runnable (Ready) -> Running -> Dead
 * Creating a thread puts it in a 'New' state (it's been created, but not actually doing anything)
 * start method puts it in the Runnable state, so it can actually run
 * While running, it is in a Running state. (When multiple ones are running, each fluctuates between Runnable and Running)
 * One stack per Thread
 * yield method indicates that the currently executing thread is willing to stop running on the CPU to allow others to execute


 * Think of the run method as the progress bar of the thread
 * If you have several run methods, you'll have different threads competing with each other

Thread States

 * Run method is the individual progress bar
 * The start method notifies the Thread that it is 'alive'
 * The start method puts a thread in runnable/runnable state
 * The run method that is called from the start method, puts it in the Running state
 * the sleep method puts it in the Sleeping state
 * in this period the other threads are running
 * goes back to the Ready state when it's finished being in the Blocked state
 * Blocked state is when a Thread is waiting for an IO for example
 * in this period the other threads are running
 * goes back to the Ready state when it's finished being in the Blocked state
 * Waiting is related to synchronisation

Benefits of Multithreading

 * Deals with several tasks at once
 * Improves responsiveness
 * Utilises multiple cores
 * Perform background tasks

Maven

 * It's a build and configuration tool
 * Driven by a central repository
 * Pom stands for Project Object Model

Hazards

 * Deadlock
 * Both threads are looking for a resource, which they can't get to
 * A situation where one thing is looking for a resource it can't get and the other is looking for a resource, this can't get
 * e.g. one has the pen, the other has the board. Neither can write on the board without having the other's resource
 * Livelock
 * When both things are giving a resource to each other
 * Race Condition
 * The outcome depends on the outcome of the race (which thread executes first)
 * One does addition, the other does multiplication, if one happens before the other in one scenario and the other way in the other scenario, the result will be different
 * Starvation
 * One thread keeps going while the other has to wait for resources before it can continue

Solutions public synchronized void withdrawCounter(double amount){ }
 * Atomic Operation means you don't split up a method into further bits. (All or nothing - once it's started, it'll do the transaction)

public synchronized void withdrawATM(double amount){ }

Or when synchronizing just one part of the method:

Synchronized(this){ }