owned this note changed a year ago
Linked with GitHub

Week 3

OOP: Classes and Objects

  • OOP is a programming paradigm. A programming paradigm guides programmers to analyze programming problems, and structure programming solutions, in a specific way.
Paradigm Programming Languages
Procedural Programming paradigm C
Functional Programming paradigm F#, Haskel, Scala
Logic Programming paradigm Prolog
  • Java is primarily an OOP language but it supports limited forms of functional programming and it can be used to (although not recommended) write procedural code.
  • Choose the correct statements
    • OO is a programming paradigm
    • OO guides us in how to structure the solution
    • OO is mainly an abstraction mechanism
    • OO is a programming language
    • OO is modeled after how the objects in real world work
  • Choose the correct statements
    • Java and C++ are OO languages
    • C language follows the Functional Programming paradigm
    • Java can be used to write procedural code
    • Prolog follows the Logic Programming
  • OOP views the world as a network of interacting objects.
  • OOP solutions try to create a similar object network inside the computer’s memory – a sort of a virtual simulation of the corresponding real world scenario – so that a similar result can be achieved programmatically.
  • Every object has both state (data) and behavior (operations on data).
  • Every object has an interface and an implementation.
  • A class contains instructions for creating a specific kind of objects. It turns out sometimes multiple objects keep the same type of data and have the same behavior because they are of the same kind.
  • Objects in OOP is an abstraction mechanism because it allows us to abstract away the lower level details and work with bigger granularity entities
  • An object is an encapsulation of some data and related behavior in terms of two aspects:
  1. The packaging aspect: An object packages data and related behavior together into one self-contained unit.
  2. The information hiding aspect: The data in an object is hidden from the outside world and are only accessible using the object's interface.

Java: Objects

  • System belongs to the java.lang package, which is imported automatically.
  • To create a new object, you have to use the new operator.
  • Variables that belong to an object are called attributes (or fields).
  • In an example, the variable spot is assigned a null value. As a result, trying to access spot.x attribute or invoking the spot.translate method results in a NullPointerException.
  • It is possible to have multiple variables that refer to the same object.
  • When an object is passed into a method as an argument, the method gains access to the original object.
  • Garbage Collection: no variables refer to an object.
    In Java, you don’t have to delete objects you create when they are no longer needed. As your program runs, the system automatically looks for stranded objects and reclaims them; then the space can be reused for new objects.

Java: Classes

  • The this keyword is a reference variable in Java that refers to the current object.
  • this can be used to refer to a constructor of a class within the same class too.
public Time() { this(0, 0, 0); // call the overloaded constructor } public Time(int hour, int minute, int second) { // ... }

OOP, Java: Class-Level Members

  • variables whose value is shared by all instances of a class are called class-level attributes.
  • methods that are called using the class instead of a specific instance are called class-level methods.
  • Class-level attributes and methods are collectively called class-level members. They are to be accessed using the class name rather than an instance of the class.
  • Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier.
  • The static modifier, in combination with the final modifier, is also used to define constants.
  • Explanation of System.out.println(...):
    out is a class-level public attribute of the System class.
    println is a instance level method of the out object.

Java: Useful Classes

  • An Application Programming Interface (API) specifies the interface through which other programs can interact with a software component. It is a contract between the component and its clients.
  • When developing large systems, if you define the API of each components early, the development team can develop the components in parallel because the future behavior of the other components are now more predictable.
  • Choose the correct statements
    • A software component can have an API.
    • Any method of a class is part of its API.
    • Private methods of a class are not part of its API.
    • The API forms the contract between the component developer and the component user.
    • Sequence diagrams can be used to show how components interact with each other via APIs.

The String class

  • Find characters of a string: charAt
    returns a char, a primitive type that stores an individual character (as opposed to strings of them).
  • convert a string to an array of characters: toCharArray
char[] fruitChars = fruit.toCharArray()
  • Change a string to upper/lower case: toUpperCase / toLowerCase
    a string method cannot change the string object on which the method is invoked, because strings are immutable.
    invoking the method has no effect if you don’t assign the return value to a variable.
String s = "Ada"; s.toUpperCase(); // no effect s = s.toUpperCase(); // the correct way
  • Replacing parts of a string: replace
String text = "Computer Science is fun!"; text = text.replace("Computer Science", "CS"); System.out.println(text); -> CS is fun!
  • Accessing substrings: substring
    "banana".substring(0) -> "banana"
    "banana".substring(2) -> "nana"
    "banana".substring(6) -> ""

    "banana".substring(0, 3) -> "ban"
    "banana".substring(2, 5) -> "nan"
    "banana".substring(6, 6) -> ""

  • Searching within strings: indexOf
    "banana".indexOf('a') -> 1
    "banana".indexOf('a', 2) -> 3 searches for 'a', starting from position 2
    "banana".indexOf('x') -> -1
    "banana".indexOf("nan") -> 2 searches for the substring "nan"

  • Comparing Strings: equals compareTo equalsIgnoreCase
    If the strings differ, you can use compareTo to see which comes first in alphabetical order. The return value from compareTo is the difference between the first characters in the strings that differ.If the strings are equal, their difference is zero. If the first string comes first in the alphabet, the difference is negative. Otherwise, the difference is positive.
    The uppercase letters come before the lowercase letters, so "Ada" comes before "ada".
    To check if two strings are similar irrespective of the differences in case, you can use the equalsIgnoreCase method.

  • Others:
    contains: checks if one string is a sub-string of the other e.g., Snapple and app
    startsWith: checks if one string has the other as a substring at the beginning e.g., Apple and App
    endsWith: checks if one string has the other as a substring at the end e.g., Crab and ab

  • Wrapper classes provide methods for parsing strings to other types.
    ex. Integer.parseInt("1234") -> 1234

  • Wrapper classes also provide toString, which returns a string representation of a value.
    ex. Integer.toString(1234) -> "1234"

The Arrays class

import java.util.Arrays
int[] a = new int[]{1,2,3,4}; int[] b = Arrays.copyOf(a, 3); // copy first three elements System.out.println(Arrays.toString(b)); int[] c = Arrays.copyOf(a, a.length); // copy all elements System.out.println(Arrays.toString(c)); -> [1, 2, 3] [1, 2, 3, 4]

The Scanner class

import java.util.Scanner;
  • Scanner is a class that provides methods for inputting words, numbers, and other data.
  • nextLine that reads a line of input from the keyboard and returns a String.
public class Echo { public static void main(String[] args) { String line; Scanner in = new Scanner(System.in); System.out.print("Type something: "); line = in.nextLine(); System.out.println("You said: " + line); } }

Code Quality: Naming

  • Proper naming improves the readability. It also reduces bugs caused by ambiguities regarding the intent of a variable or a method.
  • Use nouns for classes/variables and verbs for methods/functions.
  • Avoid foreign language words, slang, and names that are only meaningful within specific contexts/times.
  • A name is not just for differentiation; it should explain the named entity to the reader accurately and at a sufficient level of detail.
  • If the name has multiple words, they should be in a sensible order.
  • Related things should be named similarly, while unrelated things should NOT.

RCS: Using History

  • RCS tools store the history of the working directory as a series of commits.
  • To see what changed between two points of the history, you can ask the RCS tool to diff the two commits in concern.
  • To restore the state of the working directory at a point in the past, you can checkout the commit in concern.
  • You can use the git's stash feature to temporarily shelve (or stash) changes you've made to your working copy so that you can work on something else, and then come back and re-apply the stashed changes later on.
Select a repo