

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


Introduction Procedural Programming Emphasis: tasks Top-down design: Break problem → tasks Access-Data: share, vulnerable ( trace) Object-Oriented Programming Emphasis: data Bottom-up design: Break problem → entities (obj) of OOP Modularity: obj can be written & maintained independently Information hiding: hide obj’s internal implementation Code re-use: class can be reused directly / by inheritance Pluggability: Problematic obj can be replaced individually Abstraction Represent essential feature ( bg details) Only necessary, common property of obj (problem dependent) Essential in design of classes & objs Encapsulation Wrap up data & operation into one unit Hide the implementations from others Data access directly from outside an obj (information hiding) Interact with obj only via exposed interface (public methods) Allow changing internal implementation of an obj X hurt the overall system Essential in implementing class & object Inheritance The process by which objects of one class acquire the properties of objects of another class Sub-class automatically inherit all the properties of super-class (instance var + method) IS-A relationship (1-direction) between sub-class & super-class Specialization of super-class (override method) Avoid duplicate code multiple inheritance Inheritance (Instance Variable) overridden Hidden → both exist, see super-class’s var (sub-class’s var have same name with super-class’s var) Inheritance (Access Control) Inherited: public private (still there, X access directly, need via public getter/setter) Access level Access modifier Class Package Sub-class World private private Y N N N default (none) Y Y N N protected protected Y Y Y N public public Y Y Y Y Inheritance (Method Overriding) Same argument list Compatible return type less accessible Method Overloading related to inheritance/polymorphism Same name Different args list Can different return types/access level Polymorphism Take more than one form Compiler decide if method can be call is based on ref type, not actual obj type (super-class reference use sub-class’s method)
Garbage Collection Heap: mem each time an obj is created go into Allocates mem space on heap according to space that obj need Java manage mem for you When obj used again → eligible for garbage collection Garbage collection is unpredictable, usually when mem is low Java Platform independent: Java program compiled → platform independent byte code → executed by JVM Architectural-neutral: Compiler generate archi-neutral obj file → compiled code (executable on many processors) Portable: (becuz of the above 2) Robust (strong): have compile + runtime error checking Multithreaded: do tasks simultaneously Strongly-typed: change var type assign value to var ( same type) (int/byte/float/… → same) Main() Method return type Accept any num of args from cmd line Do only 2 thing → Create a obj & call a method (most Java app) Primitives and References Data Types Primitive: Type Bit Depth Value Range boolean JVM-specific true / false char 16 bits 0 – 65535 byte 8 bits - 128 – 127 short 16 bits - 32768 – 32767 int 32 bits - 2147483648 – 2147483647 long 64 bits - huge – huge float 32 bits varies double 64 bits varies floating num is treated as double e.g. float f = 32.5f; specify this num is float Obj references: references to objs Type Conversion Compiler allow assign value (wider range type) to var (narrower range type) → may result in information loss Type Casting tells compiler it is intended → error reporting e.g. float f = (float) 32.5; e.g. if(obj instanceof Snowboard) { Snowboard sameObj = (Snowboard) obj; } Array Must decide size when create ( change) Array is obj with (only 1) instance var (length) + method State and Behavior of an Object Methods: Parameters & Arguments Parameters: placeholders (sth like local variables) Arguments: actual value passed into the method when calling Mechanism: pass-by-value Constructor Call: automatically when create object & before assigned to a reference. explicitly call Default: empty + no arguments assumed when >1 constructors is defined Inheritance: not inherited. Auto call super-class’s constructor when create sub-class object. “super()” to call explicitly Static Method depend on & use any instance variable Can run without instance use non-static methods Called using class name e.g. Math.round(3.14); Static Variable Shared by all instances of that class Initialization: when the class is first loaded each time an instance is made before any object of that class can be created before any static method of the class runs Accessed using class name e.g. double d = Math.PI; Can be used in static methods Final Variable: change after initialized default value Must be initialized at declaration/in the constructor Constant: e.g. public static final double PI = 3.14; Must be initialized at declaration / in a static initializer Method: be overwritten by sub-class Class: be extended = sub-classes Static initializer Runs as soon as the class is loaded Before: any static method can be called any static variables can be used e.g. public static final int abc; static { abc = 123; } Java API ArrayList ArrayList
Connection Streams & Chain Streams Connection Stream: connection to source/destination (e.g. file, network socket) low-level method for serialization (e.g. bytes → destination) Chain Streams: works only if chained to another stream higher-level methods for serialization (e.g. obj → o/ stream) Flexibility: mix & match streams Serializable Interface Marker/tag interface becuz method to implement If any super-class is serializable, subclass is also serializable Transient Instance Variables Some obj depend on runtime-specific info → shud save e.g. network connections, threads, file obj … Skipped by the serialization process Given default values when deserialized e.g. transient String currentID; Deserialization data is read from the stream JVM decide the obj’s class type by serialized obj’s stored info If find/load the class, throw exception & deserialization fail New obj is created on the heap, but constructor run If the obj has a non-serializable super-class, the no-argument constructor for that class will run, along with any constructors above it Instance var of the obj are given value from serialized state Version Control Each time an obj is serialized, it is ‘stamped’ with a serialVersionUID (about the class structure) Different serialVersionUID when the class has been modified serialVersionUID is compared when deserialized match → exception Assign a value → keep the same serialVersionUID e.g. private static final long serialVersionUID = 63…; Changes to a class that can hurt deserialization Changes to a class that are usually OK Delete an instance var Add new instance var to the class (existing objs will deserialize with default values for the instance var they didn’t have when they were serialized) Change the declared type of an instance var Change the access level of an instance var Change a non-transient instance variable to transient Change an instance var from transient to non- transient (previously-serialized objs will have default value for the previously-transient var) Move a class up or down the inheritance hierarchy Add/Remove classes to the inheritance tree Change a class (anywhere in the obj graph) from serializable to non-serializable Change an instance var to static Networking and Multi-threading Client-Server Model Client A connects to the server Server make a connection & add client A to the list of parti Client A send a message to server Server distribute the message to ALL parti (including Client A) Socket Connection Socket (java.net.Socket class) is an obj that represents a connection b/t 2 app which may/ run on 2 distinct machines TCP Port 16 - bit unsigned number assigned to a specific server app 1 program running on 1 TCP port only >1 program → bind → java.net.BindException Reserved: 0 to 1023 e.g. HTTP(80), Telnet(23), FTP(20) Available: 1024 – 65535 Reading Data from a Socket Writing Data from a Socket Multi-threading A thread can be considered as a line of execution. Has its own call stack → store method invocations and local var The main thread create additional (worker) threads to handle tasks in parallel e.g. Runnable threadJob = new MyRunnable(); Thread myThread = new Thread(threadJob); myThread.start();) Runnable Interface A Runnable object is to a Thread object what a job is to a worker only 1 method e.g. run(); States of a Thread Thread Scheduler guarantee about scheduling & API on the scheduler → control Sleep Help threads take turns by putting them to sleep periodically Force it to leave the running state → let other thread to run wake up before the specified duration (milliseconds) Go to runnable state when wake up e.g. try { Thread.sleep(2000); } catch (Exception e) {…} Concurrency Problem When >=2 threads have access to the same object on the heap Result in a race condition → may cause data corruption Synchronization Guarantee that the thread (with key) can wake up and finish the method before any other thread can access e.g. private synchronized void makeWithdrawal(int amount) { ... } Object’s Lock Every Java obj has a lock with a single key A thread can enter one of the synchronized method only if it has the obj’s key If an obj has >1 synchronized method, there is still only 1 key Deadlock Problem When two threads are holding a key the other thread wants → forever wait Java has no mechanism to handle deadlock Exception Handling Exception Method can throw an exception when something fails at runtime An exception is an obj of type Exception/any of its sub-classes When a method throws an exception, that method is popped off the stack immediately, and the exception is thrown to the next method down the stack Handling Exceptions try/catch block Compiler care how, but only that exception is handled Code below the catch block continues (no matter exception is thrown) Finally Block When try/catch block complete → finally block runs → then method continue Even if try/catch block has a return statement, the finally block still run Unchecked Exceptions RuntimeExceptions (& sub-classes) are not checked by the compiler check a method declares that it throws a RuntimeException or not caller have try/catch block or not Mostly from code logic e.g. casting a reference into an incompatible type Checked Exceptions All exceptions ( RuntimeException & sub-classes) are checked by compiler Method that might throw a checked exception must announce it with a throws- exception declaration Ducking Declare the method will throw exceptions rather than handle it by try/catch Ducker pop off the stack directly and exception is thrown to the next method Exception Rules have a catch or finally block without a try block put code between the try block and the catch block try block must be followed by either catch/finally block, or both try block with only a finally block = ducker (follow above rules for ducker) Multiple Exceptions Method can throw >1 exceptions (declare all the checked exception thrown) >=2 exceptions have common super-class → method can declare/catch just the super-class Life and Death of an Object Stack Set aside as a scratch space for a thread of execution Store method invocations and local var Last-In-First-Out (LIFO) Heap Set aside for dynamic allocation Garbage-collectible Where all obj live Instance Variable Live inside the obj they belong to → also live on the heap Constructor Super-class constructors must finish before its sub-class constructor super() must be 1st statement this(): call a constructor from another overloaded constructor in the same class only be used in constructor either super()/this(), both Simple Chat Server import java.io.; import java.net.; import java.util.; public class SimpleChatServer { ArrayList