Samenvatting - College 1 T/m 18 | Object-oriented programming PDF

Title Samenvatting - College 1 T/m 18 | Object-oriented programming
Author Carmen van Veen
Course Object-oriented Programming
Institution Technische Universiteit Delft
Pages 27
File Size 687 KB
File Type PDF
Total Downloads 4
Total Views 171

Summary

Object-Oriented ProgrammingsummaryCollege 1: First StepsData:  Integers 23, -45, 0 o Int (32 bit) o Byte (8 bit) o Short (16 bit) o Long (64 bit)  Real numbers 55, 2. o Double (64 bit) o Float (32 bit)  Letters/numbers/punctuation marks ‘a’, ‘?’, ‘5’ o Char (16 bit)  Text (strings) ‘Hello World’...


Description

Object-Oriented Programming summary College 1: First Steps Data:  Integers o Int o Byte o Short o Long  Real numbers o Double o Float  Letters/numbers/punctuation marks o Char  Text (strings) Composed data:  Ordered pair  Set  Sequence

23, -45, 0 (32 bit) (8 bit) (16 bit) (64 bit) 55.4, 2.52 (64 bit) (32 bit) ‘a’, ‘?’, ‘5’ (16 bit) ‘Hello World’ (3,5) {“jan”, “els”, “marie”} [4, 5, 6, 7]

Storage of data  data is stored in bytes (rows of 8 bits)  2 bits is 22 = 4 different combinations, 4 bits is 24 = 16 different combinations.

College 2: Programming Structures Write readable programs: 1. Structure your program 2. Cohesion: show parts that logically belong together 3. Separation: use spaces, empty lines, capital/smaller letters 4. Indentation: to show that certain parts belong together 5. Comments: use comments to explain 6. Identifiers: use identifier names that clearly express the role of the identifier Lazy operators  && and || :  a && b  if a is false it won’t check b, because it already will be false no matter the truth value of b.  a || b  if a is true it won’t check b, because it already will be true no matter the truth value of b.

Workflows:  Selection: o If-statement: If () ; o If/else-statement: If () ; else ; o Switch-statement: table with limited number of values: int number = …; char res = ‘ ‘; switch(number) { case 1: res = ‘A’; case 2: res = ‘B’; case 3: res = ‘C’;  Iteration: o Repetition:  Counter : int row = 0;  Increment: row = row + 1;  (stopping)condition: row == 8; o For-statement: for(, , ) ; o While-statement: ; while(){ ; ;} o Do/while-statement: do{//statements} while();  Will be executed at least one time

College 3: Methods Some methods:  Method max(): +(visibility) max (method name) (x: int, y: int (parameters: name and type)) : int(return) o Pre (defines the initial state before the calculation in the method): true o Post(defines the end state after the calculation in the method): returns the largest element of the set {x,y}  Method min(): + min (x: int, y: int) :int o Pre: true o Post: returns the smallest element of the set {x,y}





Method isEven(): + isEven(x: int) :Boolean o Pre: true o Post: returns true if and only if x is even Method sum(): +sum(x: int, y: int, z: int) :int

College 4: Debugging Debugging:  Breakpoints  if you run ‘debug’, the VM will pause the program just before executing the statement marked with the breakpoint  blue circle in margin  double click in margin to add breakpoint  Eclipse’s debug view: o Green triangle  continue executing until the next breakpoint or if there is none, until the end o Red square  stopping execution o First yellow arrow  stepping into  look what is happening inside a method call o Second yellow arrow  step over  step over the statement  Breakpoint on entire class  debugger will suspend execution when something from the class is called

College 5: Classes A class is a software module that is composed of attributes and methods(i.e., data and operations) Point = name of the class - x: double = attributes (i.e. data) - y: double + getX(): double = methods(i.e. the operations on the data + getY(): double Class versus object:  A class is a blueprint for objects; it defines: o Attributes o Methods  An object is an instance of a class, with its own values for the attributes How does a static work:  A static method does not work on an object, which implies: o No reference to “this”

 

o No access to attributes (it can access static attributes) A static attribute is common to all objects of a class Static works at the level of a class

Difference between private and public:  Private  other classes cannot access it  Public  other classes can access it Public static void main (String [] args):  Public: accessible to all  Static: works at the level of a class, not the object  Void: no return value  Main: “ can be called externally”  String [] args: an array of Strings

College 6: Arrays Arrays  for storing (a lot of) similar (or the same) data:  Declaration  int[] row  Memory allocation  new int[4]  Binding  int[] row = new int [4]  Filling in or requesting data from 1 cell  row[i] Some methods using arrays:  Method for only printing even numbers: for (int i = 0; i < array.length; i = i + 1) if ( array[i] % 2 == 0) System.out.println(array[i] + “ “); System.out.println();  Method for swapping two values on the first and second place of an array: public static void swap (int[] row){ int temp = row [0]; row [0] = row [1]; row [1] = temp; }  Method to find the maximum value of a array: public static int max(int[] row) { int n = row.length; int max = Integer.MIN_VALUE; for(int i = 0; i < n; i = i + 1) if (row [i] > max) max = row[i];

return max; } Recursion ( for example: i = i + 1)  within a method, you call the same method, with different parameters  important: stopping condition!

College 7: Container Classes Some different standard containers:  IntList: IntList - element: int [] - number: int + IntList(n: int) Pre: n>0 Post: if pre holds, an IntList object is created with number = 0 and capacity = n + add (el: int) Pre: number < capacity Post: el is placed at the first empty spot in the IntList and number = number + 1 + get(i: int) : int Pre: 0 30: extremely complex  Avoid long parameter lists: o Create new classes if you encounter parameter lists with a logical grouping  Check the style of you code: o Follow code conventions(indentation, whitespaces, variable/method naming, …) o Provide and maintain documentation o Use whitespace to make clear divisions in your code  About testability: o If your method has a cyclomatic complexity of 6, then you would need to write at least 6 tests to cover each path that runs through your code

College 14: Threads Why threads?  You want to do multiple things at the same time within the same program  You stay within the same program (“process”), so has its own memory space Threads vs. processes:  A process = a running program  In a computer multiple processes run in parallel  Normally, each process has its own piece of private memory  you can pass information between processes (e.g. through sockets)  Within 1 process you can also do things “at the same time”  threads  you are working in the same piece of memory Concurrency vs. parallelism:  Concurrency  doing many things at the same time  Parallelism  splitting one big job on multiple processors: o Within 1 program  With 1 processor?  interleaving:  Each thread gets a bit of time  Order of threads is not pre-determined  Heisenbugs  bugs that appear because of different expectations w.r.t. thread scheduling  With >1 processor?  With processors that have hyper threading Multi-threading:  Not necessary  Risky  Useful for trivially parallelizable problems (serving web pages, processing multiple files with the same algorithm) The class Thread (constructor):  Provides methods for constructing and managing threads  Is not a thread itself  The class contains this method: public native synchronized void start() o This is where the new thread is started o But what will it do?  The class Thread has a method: public void run()  That is (almost) empty  Redefine it in a subclass  The instructions in run() are the things that this thread will do



 BUT: you call run() through start() The order of thread execution: o Is not guaranteed o Is done by the scheduler (= operating system) o A different outcome on different operating systems

It is not possible to extend from Frame and from Threads  you’ll have to change the extend from Threads into an interface Runnable: Here you see something is started and then the run(mini main method) method is called and the second thread starts executing.

Public class Alternative implements Runnable { Private Thread fThread; Public Alternative() { fThread = new Thread(this); fThread.start();}

this implements Runnable

Public void run(){ //do something}} Synchronization:  What happens if two threads access the same data at the same time?  one overrides the other  depending on the scheduler there are multiple options  Within an object only 1 thread can be activated in a synchronized method  so as soon as 1 thread enters a synchronized method of an object O, no other thread can enter a synchronized method of O  deadlock (= two threads are competing for resources, but it can happen that they are waiting for each other)  program stops working

How to use synchronized: Public class SynchronizedCounter { Private int c = 0; Public synchronized void increment() { c++; }

Public synchronized void decrement(){ c++; } }

College 15: Sockets ISO’s (= International Standard Organization) OSI (= Open System Interconnection) Reference model:  Reference model defines 7 layers of network protocols and strict methods of communication between layers o 7 layers because easy to change a particular technology/implementation without having to change everything Internet Protocol:  Rules for communication between devices  Transmission Control Protocol (TCP) (layer 4) o Messages between processes and needs to know:  Port (=number of process listens to) of the initiator  Port of the receiver  This identifies the process on your computer  Your webserver typically listens to port 80  Ordering of packages (if a package skipped ahead)  Flow control (to avoid congesting the receiver)  checksum  Internet Protocol (IP) (layer 3) o Packets between devices and needs to know:  Initiating device  Receiving device  Time to live  How long does a packet stay on the network before it may disappear  Checksum  calculation (hashcode) to a number which can be checked by the other device o IP-address:  Consists of 4 bytes  Is true for IPv4 but we are transferring to IPv6 (128 bits)  A name server translates the machine name into an IP address

Java can use multiple client programs with one server program (e.g. multiplayer online games):  Two important classes are used: o Socket  will do the actual communication  Public Socket (String host, int port) throws UnkownHostException,

o

IOException  creates a stream socket and connects it to the specified port number on the named host  Public InputStream getInputStream() throws IOException  Public OutputStream getOutputStream() throws IOException  Public synchronized void close() throws IOException ServerSocket  only initiates the connection. If an connection is made the rest will be delegated to the socket  public ServerSocket (int port) throws IOException  creates a server socket on a specified port  public Socket accept() throws IOException  listens for a connection to be made to this socket and accepts it  the method blocks until a connection is made  this means your program can only do 1 thing at a time  public void close() throws IOException  closes this socket

What if you more than 1 client?  Give each now client its own thread that handles all the requests of that client  Create a serversocket  Put every client in a while loop

College 16: Strings (and things) Scanner:  Works with a String, but also with a file (Stream)  With a scanner you can tokenize a String/Stream o A token can be a String, but also numbers, Booleans, etc. o You can test for the next token:  hasNext()  String?  hasNextBoolean()  Boolean?  hasNextInt()  integer?  … o Subsequently read with:  Next()  nextLine()  nextInt()

StringTokenizer:  Also resembles a Scanner, but only works with Strings and also only returns Strings: StringTokenizer st = new StringTokenizer(“this is a test”); while(st.hasMoreTokens()){ System.out.println(st.nextToken()); } Output: This is a test

String.split():  Almost the same as StringTokenizer, only is presented differently  Tokenizer enumerates  String.split returns an array o Can be useful if you need to 4 th field/token String[] result = “this is a test”.split(“\\s”); for (int x=0; x < result.length; x++) System.out.println(result[x]);

College 17: Java generics ArrayList stringlist = new ArrayList(); Stringlist.add(new String(“Student 1”)); Stringlist.add(new String(“Student 2”)); String content = stringlist.get(0); vs. ArrayList stringlist2 = new ArrayList(); Stringlist2.add(new String(“student 1”)); Stringlist2.add(new String(“student 2”)); String content2 = (String)stringlist2.get(0);

Type erasure  generic arguments are compile-time only  the runtime does not know about type specializations Public class Pair { Private A a; Private B b;} Pair p1 = new Pair (“foo”, 1); Pairp2 = new Pair (1, “foo”); System.out.println((p1 instanceof Pair)); //true System.out.println((p2 instanceof Pair)); //true Type constraint  we can place constraints to generic type arguments Public class Pair { Private A a; Private B b;} System.out.println((p1 instanceof Pair)); //true System.out.println((p2 instanceof Pair)); //fails

College 18: Event handling The problem: 1. What should happen? 2. When should this happen? 3. Who knows the answer to question 1? 4. Who knows the answer to question 2? Events are frequently used in Graphical User Interfaces (GUIs) Model of delegation:  Source  Event  knows when  Listener  knows what Firing events:  The source delegates the processing to the listener  To that end, the source calls a method of the listener  The source needs to know the signature of the method  The listener should implement an interface Where does an event come from?  The mouse send the signal: “my left button is pressed”  The operating system (e.g. Windows) catches this signal. It establishes that the cursor is within the area of the Java window.  De Java program (the JVM) gets a signal: “the left mouse button was pressed at the following coordinates within your window”  The JVM searches for the component at the designated coordinates. This component is marked as the source of the event.  It might be that multiple components are “stacked upon” each other  At least one listener that is interested in mouse events should be associated to the component.  The JVM creates an instance of the class MouseEvent and calls the method mousePressed of the listener with this instance of MouseEvent as a parameter.

What happen if...  You press a mouse button on a component that has no listener associated to it  nothing

The class EventObject:  Contains(amongst others): o Public Object getSource()  returns the source of the event...


Similar Free PDFs