Glossary
183 terms

  • abstraction
  • Activity
    In software, we have a name for these conceptual building blocks that gather up many details into a tidy package. They are abstractions. An abstraction takes something complex and, by hiding its details, presents it in a form that is simpler. We say that Version 1 is at a lower level of abstraction (more detail, simpler building blocks), and Version 3 is at a higher level of abstraction (less detail, more hidden complexity). Those details that an abstraction hides are called implementation details. Much of the work of programming is about choosing abstractions, understanding
  • Please read this document. Important concepts class object state behavior abstraction interface instance, instantiate class definition property / attribute internal state implementation details encapsulation Your response As usual, post a brief thought that does more than just summarize or repeat the reading. Some suggested topics: What was particularly interesting, confusing, or exciting to you in this reading? What terminology seems unclear or mysterious right now? If you’ve already done some object-oriented programming, what do you notice in this reading that you hadn’t thought of before?
  • implementation details
  • implementation
  • Activity
    (less detail, more hidden complexity). Those details that an abstraction hides are called implementation details. Much of the work of programming is about choosing abstractions, understanding abstractions, creating abstractions, altering abstractions, and moving between levels of abstraction. How do we take code at a lower level of abstraction, code that looks like Version 1 of the instructions, and transform it to use higher levels of abstraction like Version 2 and Version 3? What programming languge tools and technologies do we use to do that? What human thought processes and social practices do we use to do that? These questions are at the heart of COMP 127. It’s a long journey, and a journey that does not end with this course. It’s not a journey that ends at all; the software world is constantly rethinking this.
  • than its interface. You don’t have to know how a transmission or a motor works to drive a car. These implementation details of a car are hidden from the driver. What is the internal state of the car? A mechanic might have to figure it out, but the driver doesn’t. In fact, the implementation details and internal state of a car are not merely hidden from the driver; they are protected from the driver. You shouldn’t be able to rearrange the gears in the transmission or release the toxic chemicals in the battery by operating the interface of the car. If you could, we’d consider this a serious failure!
  • Activity
    are its interface or API (application programming interface). The details of how it works are its implementation. Software development mostly consists of understanding abstractions that other people have created for you, and using those abstractions to solve your problem. (Software development also consists of creating your own abstractions as your code grows — but today we’re focusing on using other people’s abstractions.) The syntax and the terminology In this activity, the code you will read and write does a surprising number of different things with just a few basic building blocks, listed in the table below. Study this table carefully! This syntax and this terminology is
  • generality
  • Activity
    Improving clarity is not the only motivation for abstraction. If done right, abstraction can also create generality and resilience. Generality is the ability for the same code to handle many situations. If “open” means different things for different doors — turning a knob versus pushing a bar, for example — Version 3 has enough generality to handle that variety. Resilience is the ability for existing code to continue working despite changes in its context. If we create a new kind of door that opens in some new way — maybe you have to turn a crank while whistling and patting your head, for example — Version 3 is
  • resilience
  • Activity
    If “open” means different things for different doors — turning a knob versus pushing a bar, for example — Version 3 has enough generality to handle that variety. Resilience is the ability for existing code to continue working despite changes in its context. If we create a new kind of door that opens in some new way — maybe you have to turn a crank while whistling and patting your head, for example — Version 3 is resilient to that change. Play Get the instructor’s attention, and let them know you’ve reached this point in the instructions. They will hand you an everyday task at a high level of abstraction, like Version 3. As a group, try rewriting it at a Version 2 or even a Version 1 level of abstraction. (
  • syntax
  • Reading
    follow these instructions to get the code on your computer and play with it. Important concepts syntax, semantics, syntax error declaration comment, whitespace floating point conditional, if statement code formatting, style Things to consider (exercises for yourself, not to turn in) What’s the answer to the puzzle at the end? If you’re not sure, what might it be? Make a guess. What experiment could you do to test that guess? What might possibly happen if you put something inside an if statement’s condition that is just a number, like if(37)? What do you think
  • semantics
  • Reading
    follow these instructions to get the code on your computer and play with it. Important concepts syntax, semantics, syntax error declaration comment, whitespace floating point conditional, if statement code formatting, style Things to consider (exercises for yourself, not to turn in) What’s the answer to the puzzle at the end? If you’re not sure, what might it be? Make a guess. What experiment could you do to test that guess? What might possibly happen if you put something inside an if statement’s condition that is just a number, like if(37)? What do you think
  • syntax error
  • Reading
    to get the code on your computer and play with it. Important concepts syntax, semantics, syntax error declaration comment, whitespace floating point conditional, if statement code formatting, style Things to consider (exercises for yourself, not to turn in) What’s the answer to the puzzle at the end? If you’re not sure, what might it be? Make a guess. What experiment could you do to test that guess? What might possibly happen if you put something inside an if statement’s condition that is just a number, like if(37)? What do you think should
  • declaration
  • Reading
    to get the code on your computer and play with it. Important concepts syntax, semantics, syntax error declaration comment, whitespace floating point conditional, if statement code formatting, style Things to consider (exercises for yourself, not to turn in) What’s the answer to the puzzle at the end? If you’re not sure, what might it be? Make a guess. What experiment could you do to test that guess? What might possibly happen if you put something inside an if statement’s condition that is just a number, like if(37)? What do you think should happen? Make a few guesses, then try it.
  • comment
  • Reading
    to get the code on your computer and play with it. Important concepts syntax, semantics, syntax error declaration comment, whitespace floating point conditional, if statement code formatting, style Things to consider (exercises for yourself, not to turn in) What’s the answer to the puzzle at the end? If you’re not sure, what might it be? Make a guess. What experiment could you do to test that guess? What might possibly happen if you put something inside an if statement’s condition that is just a number, like if(37)? What do you think should happen? Make a few guesses, then try it.
  • whitespace
  • Reading
    to get the code on your computer and play with it. Important concepts syntax, semantics, syntax error declaration comment, whitespace floating point conditional, if statement code formatting, style Things to consider (exercises for yourself, not to turn in) What’s the answer to the puzzle at the end? If you’re not sure, what might it be? Make a guess. What experiment could you do to test that guess? What might possibly happen if you put something inside an if statement’s condition that is just a number, like if(37)? What do you think should happen? Make a few guesses, then try it.
  • floating point
  • Reading
    Important concepts syntax, semantics, syntax error declaration comment, whitespace floating point conditional, if statement code formatting, style Things to consider (exercises for yourself, not to turn in) What’s the answer to the puzzle at the end? If you’re not sure, what might it be? Make a guess. What experiment could you do to test that guess? What might possibly happen if you put something inside an if statement’s condition that is just a number, like if(37)? What do you think should happen? Make a few guesses, then try it.
  • conditional
  • Reading
    Important concepts syntax, semantics, syntax error declaration comment, whitespace floating point conditional, if statement code formatting, style Things to consider (exercises for yourself, not to turn in) What’s the answer to the puzzle at the end? If you’re not sure, what might it be? Make a guess. What experiment could you do to test that guess? What might possibly happen if you put something inside an if statement’s condition that is just a number, like if(37)? What do you think should happen? Make a few guesses, then try it. What other little experiments can you try on this code?
  • type
  • operator produces different results depending on whether it is adding strings or integers? A central concern of programming languages is the type of values. Types determine what operations are allowed, and what results those operations produce. In Java, the names of those types you were just adding are String and int. Note that String is capitalized but int is not. That is not a mistake in these instructions! Java is perverse that way. Example 10 shows another situation where types matter. Guess what example 10 is going to print. Uncomment it and see if you got it right! Why does it produce that output? (Hint:
  • static typing
  • static type checking
  • all before running any of your code. Java won’t even try to run your program if it detects a type error. This is called static type checking, or just static typing. Java (and many, many other languages) do it; we call those languages statically typed. Python (and many, many other languages) don’t do it; we call those languages dynamically typed. Static type checking is one of many things Java does to prepare your code before running it. All those pre-run preparations that Java makes are called “compiling the code,” or just compilation. The tool that does that work is called the Java
  • statically typed
  • , or just static typing. Java (and many, many other languages) do it; we call those languages statically typed. Python (and many, many other languages) don’t do it; we call those languages dynamically typed. Static type checking is one of many things Java does to prepare your code before running it. All those pre-run preparations that Java makes are called “compiling the code,” or just compilation. The tool that does that work is called the Java compiler. An error, such as a type checking error, that happens during compilation (and thus prevents the program from running at all) is called
  • dynamically typed
  • statically typed. Python (and many, many other languages) don’t do it; we call those languages dynamically typed. Static type checking is one of many things Java does to prepare your code before running it. All those pre-run preparations that Java makes are called “compiling the code,” or just compilation. The tool that does that work is called the Java compiler. An error, such as a type checking error, that happens during compilation (and thus prevents the program from running at all) is called compile error. That “subtract a string” code doesn’t compile
  • compile
  • compilation
  • compiling
  • Static type checking is one of many things Java does to prepare your code before running it. All those pre-run preparations that Java makes are called “compiling the code,” or just compilation. The tool that does that work is called the Java compiler. An error, such as a type checking error, that happens during compilation (and thus prevents the program from running at all) is called compile error. That “subtract a string” code doesn’t compile. Static typing comes with big tradeoffs: it can make code harder to write and harder to read; it can also help catch pernicious problems before they cause disasters. Some programmers love it. Some programmers hate it. The best programmers know how to work both with
  • compiler
  • compiling the code,” or just compilation. The tool that does that work is called the Java compiler. An error, such as a type checking error, that happens during compilation (and thus prevents the program from running at all) is called compile error. That “subtract a string” code doesn’t compile. Static typing comes with big tradeoffs: it can make code harder to write and harder to read; it can also help catch pernicious problems before they cause disasters. Some programmers love it. Some programmers hate it. The best programmers know how to work both with
  • compile error
  • . An error, such as a type checking error, that happens during compilation (and thus prevents the program from running at all) is called compile error. That “subtract a string” code doesn’t compile. Static typing comes with big tradeoffs: it can make code harder to write and harder to read; it can also help catch pernicious problems before they cause disasters. Some programmers love it. Some programmers hate it. The best programmers know how to work both with and without it. One of the best things you can do for yourself as a beginning programmer is to gain early experience in both a dynamically typed and a statically typed language. Both kinds are very common, and you are likely to encounter both. This is one of the reasons why we teach COMP 123 in Python and COMP 127 in Java here at Macalester.
  • operator
  • , but if you’re curious and hungry for more, or you’d like some more traditional reading to supplement the code): Java tutorial: Primitives Java tutorial: Operators Important concepts operator limits of int types, overflow boolean value primitive type vs object type method, method call, receiver equality operator (==) vs. equality method (.equals) for strings Things to consider (exercises for yourself, not to turn in) Ponder the puzzles at the end of PrimitiveTypes.java. What questions do you have? What might the AST for this code from the reading look like? mascot.repeat(3) What about this?
  • overflow
  • Java tutorial: Primitives Java tutorial: Operators Important concepts operator limits of int types, overflow boolean value primitive type vs object type method, method call, receiver equality operator (==) vs. equality method (.equals) for strings Things to consider (exercises for yourself, not to turn in) Ponder the puzzles at the end of PrimitiveTypes.java. What questions do you have? What might the AST for this code from the reading look like? mascot.repeat(3) What about this? (mascot + "!").repeat(
  • boolean value
  • Java tutorial: Operators Important concepts operator limits of int types, overflow boolean value primitive type vs object type method, method call, receiver equality operator (==) vs. equality method (.equals) for strings Things to consider (exercises for yourself, not to turn in) Ponder the puzzles at the end of PrimitiveTypes.java. What questions do you have? What might the AST for this code from the reading look like? mascot.repeat(3) What about this? (mascot + "!").repeat(3) What about this?
  • primitive type
  • Java tutorial: Operators Important concepts operator limits of int types, overflow boolean value primitive type vs object type method, method call, receiver equality operator (==) vs. equality method (.equals) for strings Things to consider (exercises for yourself, not to turn in) Ponder the puzzles at the end of PrimitiveTypes.java. What questions do you have? What might the AST for this code from the reading look like? mascot.repeat(3) What about this? (mascot + "!").repeat(3) What about this? mascot
  • object type
  • Important concepts operator limits of int types, overflow boolean value primitive type vs object type method, method call, receiver equality operator (==) vs. equality method (.equals) for strings Things to consider (exercises for yourself, not to turn in) Ponder the puzzles at the end of PrimitiveTypes.java. What questions do you have? What might the AST for this code from the reading look like? mascot.repeat(3) What about this? (mascot + "!").repeat(3) What about this? mascot.substring(0
  • method
  • operator limits of int types, overflow boolean value primitive type vs object type method, method call, receiver equality operator (==) vs. equality method (.equals) for strings Things to consider (exercises for yourself, not to turn in) Ponder the puzzles at the end of PrimitiveTypes.java. What questions do you have? What might the AST for this code from the reading look like? mascot.repeat(3) What about this? (mascot + "!").repeat(3) What about this? mascot.substring(0, 2).repeat(
  • method call
  • limits of int types, overflow boolean value primitive type vs object type method, method call, receiver equality operator (==) vs. equality method (.equals) for strings Things to consider (exercises for yourself, not to turn in) Ponder the puzzles at the end of PrimitiveTypes.java. What questions do you have? What might the AST for this code from the reading look like? mascot.repeat(3) What about this? (mascot + "!").repeat(3) What about this? mascot.substring(0, 2).repeat(100)
  • Activity
    . Create a new object that is a Cat, and make the felix variable point to it.” felix.meow() method call (n) call the meow method of felix (v) “Find whatever object felix currently is pointing to, and ask that object to meow / send it the meow message.” Spot these building blocks in the code, and practice using the proper terminology to describe them out loud as you work with your partner: ❌ “Now type ‘Cat felix equals…’” ✅ “Let’s declare a Cat variable named felix, and initialize it to…” The extra words are worth it: they will allow you to communicate better with other developers, construct better web searches for your programming questions, read documentation better, and more easily transfer your object-oriented programming knowledge to new languages.
  • receiver
  • limits of int types, overflow boolean value primitive type vs object type method, method call, receiver equality operator (==) vs. equality method (.equals) for strings Things to consider (exercises for yourself, not to turn in) Ponder the puzzles at the end of PrimitiveTypes.java. What questions do you have? What might the AST for this code from the reading look like? mascot.repeat(3) What about this? (mascot + "!").repeat(3) What about this? mascot.substring(0, 2).repeat(100) We haven’t covered this in class yet, or in the readings. Just take a guess! What do
  • method chaining
  • Activity
    In the third example, one method call’s result becomes the receiver of another method call, a code pattern we call method chaining: mascot.substring(0, 2).repeat(100) Do these diagrams make sense? Check with a preceptor or instructor if you’re not feeling confident. Think about that first example again: mascot.repeat(3) How do we know that a repeat method is available? If we want to know what methods are available, where do we look? How do we find them? Let’s draw another AST, but this time, labeling the types instead of the values:
  • method signature
  • Activity
    To figure that out, take a look at that documentation for repeat. You will see a line like this: public String repeat(int count) That is a method signature. It tells us four things: public Anyone code can use this method. String If you call this method, it returns a String. repeat The name of this method is “repeat.” int count The method takes one argument, which must be an int. So, what does belong at the top of that AST? Is is item 2 in that list, the return type, that answers the question: the repeat method will return a String. In this activity, you will use this kind of thinking to make sense of Java’s documentation for
  • list
  • Reading
    the instructions for doing that.) Read this short text about software testing. Important concepts list for-each loop scope zero-based indexing mutable vs. immutable manual test vs. automated test unit test vs. integration test Things to consider (exercises for yourself, not to turn in) In the nested loops example, try swapping lines 90 and 91 (i.e. switch which loop is inside and which loop is outside). How does the output change? Why? Why would you guess it might be useful to have immutable lists? Shouldn’t all lists be mutable, just in case?
  • for-each loop
  • Reading
    the instructions for doing that.) Read this short text about software testing. Important concepts list for-each loop scope zero-based indexing mutable vs. immutable manual test vs. automated test unit test vs. integration test Things to consider (exercises for yourself, not to turn in) In the nested loops example, try swapping lines 90 and 91 (i.e. switch which loop is inside and which loop is outside). How does the output change? Why? Why would you guess it might be useful to have immutable lists? Shouldn’t all lists be mutable, just in case?
  • Reading
    . (Remember to run the code for yourself, see what it does, and try experimenting with it. Here are the instructions.) Important concepts for-each loop while loop C-style for loop break, continue infinite loop off-by-one error Things to consider (exercises for yourself, not to turn in) What is the purpose of each of the three expressions that appear in the control line of a C-style for loop? The reading mentions three common looping patters that we use in programming: Pattern name Java idiom Java syntax repeat until sentinel while loop while(___) { ... }
  • scope
  • Reading
    Read this short text about software testing. Important concepts list for-each loop scope zero-based indexing mutable vs. immutable manual test vs. automated test unit test vs. integration test Things to consider (exercises for yourself, not to turn in) In the nested loops example, try swapping lines 90 and 91 (i.e. switch which loop is inside and which loop is outside). How does the output change? Why? Why would you guess it might be useful to have immutable lists? Shouldn’t all lists be mutable, just in case?
  • You should skip sections 6.3.3, 6.3.4, 6.3.5, and 6.3.6 (6.3.3 to the end of the 6.3 subsection), which are concepts that we will not be using in this course. Important concepts class, object state behavior scope encapsulation instance variable (a.k.a member variable, or in Java, field) visibility, access control getter and setter (a.k.a. accessor and mutator) Things to consider (exercises for yourself, not to turn in) Every class defines a constructor method (possibly implicitly). What is the purpose of a constructor? Assume you are given code for a class called “Button” that represents a button on your screen. The Button constructor method takes four parameters: double xPosition, double yPosition, double width, double height. Write a single line of code to create a Button variable and initialize it at position (100, 200) with a width of 30 and a height of 20.
  • zero-based indexing
  • Reading
    this short text about software testing. Important concepts list for-each loop scope zero-based indexing mutable vs. immutable manual test vs. automated test unit test vs. integration test Things to consider (exercises for yourself, not to turn in) In the nested loops example, try swapping lines 90 and 91 (i.e. switch which loop is inside and which loop is outside). How does the output change? Why? Why would you guess it might be useful to have immutable lists? Shouldn’t all lists be mutable, just in case?
  • mutable
  • Reading
    this short text about software testing. Important concepts list for-each loop scope zero-based indexing mutable vs. immutable manual test vs. automated test unit test vs. integration test Things to consider (exercises for yourself, not to turn in) In the nested loops example, try swapping lines 90 and 91 (i.e. switch which loop is inside and which loop is outside). How does the output change? Why? Why would you guess it might be useful to have immutable lists? Shouldn’t all lists be mutable, just in case? Your response What was particularly interesting, confusing, or exciting to you in this reading?
  • Activity
    bicycle. To model this, we will add an immutable instance variable to Bicycle. When something is mutable, that means it can change. “Mutable data” or “mutable state” might have one value now, but a different value in the future. When something is immutable, that means it cannot change. It might eventually disappear, but as long as that data or that state exists, it will always have the same value. Here again is the syntax for making drag a constant shared by all bicycles: private static final double DRAG = 0.1; // constant Here is the syntax for making it a
  • immutable
  • Reading
    Important concepts list for-each loop scope zero-based indexing mutable vs. immutable manual test vs. automated test unit test vs. integration test Things to consider (exercises for yourself, not to turn in) In the nested loops example, try swapping lines 90 and 91 (i.e. switch which loop is inside and which loop is outside). How does the output change? Why? Why would you guess it might be useful to have immutable lists? Shouldn’t all lists be mutable, just in case? Your response What was particularly interesting, confusing, or exciting to you in this reading?
  • Activity
    , that means it can change. “Mutable data” or “mutable state” might have one value now, but a different value in the future. When something is immutable, that means it cannot change. It might eventually disappear, but as long as that data or that state exists, it will always have the same value. Here again is the syntax for making drag a constant shared by all bicycles: private static final double DRAG = 0.1; // constant Here is the syntax for making it a mutable part of each individual bicycle’s state: private double drag = 0.1; // mutable state Other than changing the name to lowercase, which is only a matter of style, what is the difference here? Two words:
  • manual test
  • different approaches to testing, and many different goals testing might have. Because there are so many kinds of tests, developers have many ways of describing and categorizing them, and have invented many different terms to describe them. This reading will introduce you to just a few of those terms. One important distinction is manual vs. automated testing: Manual test / interactive test: A human interacts with the code in an ad-hoc way by inputting data and observing the results. They might make up tests as they go along, or they might run through a written checklist. Advantages: easy to set up, encourages exploratory testing, can catch problems that the tester wasn’t even looking for but happened to notice Disadvantages: time-consuming, not easy to repeat, may not be perfectly consistent or thorough every time, easy to miss things
  • automated test
  • time-consuming, not easy to repeat, may not be perfectly consistent or thorough every time, easy to miss things Automated test: a developer writes test code that runs through a predetermined list of test cases, and checks that the code being tested produces the correct result for each one. In other words, the programmer writes code to test other code. Advantages: consistent for different people, consistent over time, tests run fast so it makes sense to test often, excellent for catching regressions (things that used to work, but don’t work anymore) Disadvantages: only tests what the test code is looking for, coding tests is time-consuming, test code has to be maintained just like other code and may become a burden, some kinds of tests are hard to automate
  • unit test
  • unit testing
  • only tests what the test code is looking for, coding tests is time-consuming, test code has to be maintained just like other code and may become a burden, some kinds of tests are hard to automate Another important distinction is unit vs. integration testing: Unit test: A test to verify that one individual part of the software works in isolation. For example: “Does the doorknob turn? Does the door hinge swivel?” Integration test: A test to verify that many pieces work when they are all put together. For example: “If I turn the knob and pull, does the door open?” To appreciate the distinction between these two, watch this video entitled Two Unit Tests, Zero Integration Tests. You have already done some manual testing
  • Activity
    A good strategy for testing software is to test small pieces first, and make sure they work in isolation. Recall from the reading that this is unit testing. In this activity, the units of code that we are testing are static methods. How will we test them? Think about the string activity. Remember how you had to manually inspect output in the terminal to make sure that the actual output matched the expected result? In full-scale software projects, it is common for tests to contain thousands of “expected vs. actual” comparisons like this. Can you imagine manually inspecting test output on a project like that?!
  • integration test
  • : A test to verify that one individual part of the software works in isolation. For example: “Does the doorknob turn? Does the door hinge swivel?” Integration test: A test to verify that many pieces work when they are all put together. For example: “If I turn the knob and pull, does the door open?” To appreciate the distinction between these two, watch this video entitled Two Unit Tests, Zero Integration Tests. You have already done some manual testing. In our next in-class activity, you will be working with automated unit tests for the first time in this class.
  • testing
  • Testing is the process of ensuring that something functions as people want it to function. The Testing Mindset Testing is a crucial part of software development. Beginning developers (and bad project managers) often view testing as an afterthought — “first build it, then make sure it works” — but for the expert, testing is a central part of the entire software development process, right from the very beginning. When people are first learning to code, just getting the code to work
  • interactive test
  • different approaches to testing, and many different goals testing might have. Because there are so many kinds of tests, developers have many ways of describing and categorizing them, and have invented many different terms to describe them. This reading will introduce you to just a few of those terms. One important distinction is manual vs. automated testing: Manual test / interactive test: A human interacts with the code in an ad-hoc way by inputting data and observing the results. They might make up tests as they go along, or they might run through a written checklist. Advantages: easy to set up, encourages exploratory testing, can catch problems that the tester wasn’t even looking for but happened to notice Disadvantages: time-consuming, not easy to repeat, may not be perfectly consistent or thorough every time, easy to miss things
  • regressions
  • consistent for different people, consistent over time, tests run fast so it makes sense to test often, excellent for catching regressions (things that used to work, but don’t work anymore) Disadvantages: only tests what the test code is looking for, coding tests is time-consuming, test code has to be maintained just like other code and may become a burden, some kinds of tests are hard to automate Another important distinction is unit vs. integration testing: Unit test: A test to verify that one individual part of the software works in isolation. For example: “Does the doorknob turn? Does the door hinge swivel?”
  • static method
  • class method
  • Activity
    “Static method?” What exactly the “static” part means will make more sense in a few weeks. For now, just know that a static method in Java is a kind of function, one that you can call freely without having to provide additional context. Suppose you have this code: public class TextGeneration { public static String makeNonsenseWord(int letters) { ... } } …then: If you are inside of TextGeneration, you can call the static method just like you would call a function in Python: makeNonsenseWord(12) If you are in a different class somewhere else in the project, you call the static method by first specifying which class it is inside, like this:
  • Activity
    Java syntax What it’s called What it means static static variable / static method (n) “There is only one of this thing in our whole world. It belongs to the whole class, not to any particular object.” Alas, the word “static” means several completely different and unrelated things in programming. Sorry! Here we are talking about static variables and static methods. In this context, “static” means “there is just one of it;” it is the opposite of “instance:” static variable → just one of it instance variable → each object has its own
  • Reading
    Important concepts local variable, instance variable, static variable / class variable static method / class method dependency is-a vs. has-a The special “this” variable types of testing Things to consider (exercises for yourself, not to turn in) If you program a class and you do not code a constructor, does the class have a constructor? (OK, this one is from the tail end of 5.4 on last reading, but it’s good to revisit.) Describe in your own words the difference between static (class) and non-static (instance) methods. In what situations might method overloading be helpful?
  • test-driven development
  • TDD
  • Activity
    See if you can find the bug, but when you do… Do not fix the bug yet! We are going to use a technique called test-driven development, or TDD for short. If you want to make any change whatsoever in your applications functionality — adding a feature, fixing a bug, anything! — then TDD says: Run all the tests to make sure they pass. Don’t skip this step! Your teammates might have left the tests broken by accident. You want to catch this right away, or it will be confusing! Write a test that fails because you haven’t implemented your change yet. Run your new test to make sure it fails.
  • stack trace
  • Activity
    the error was. The long chain of lines that start with “at” describe where the error occurred. This is called a stack trace. The first stack trace line that mentions our code (instead of the inner workings of Java itself) is this one: testingbasics.TypoFixer.fixTypos(TypoFixer.java:20) That tells us that the occurred on line 20 of the file TypoFixer.java. (The line number may be different for you, depending on how you modified this file to add the “cs” case.) This is good! We know that some code on line 20 produced that error message. Take a look at the code. What went wrong?
  • while loop
  • Reading
    . (Remember to run the code for yourself, see what it does, and try experimenting with it. Here are the instructions.) Important concepts for-each loop while loop C-style for loop break, continue infinite loop off-by-one error Things to consider (exercises for yourself, not to turn in) What is the purpose of each of the three expressions that appear in the control line of a C-style for loop? The reading mentions three common looping patters that we use in programming: Pattern name Java idiom Java syntax repeat until sentinel while loop while(___) { ... } do n times C-style for loop
  • C-style for loop
  • Reading
    . (Remember to run the code for yourself, see what it does, and try experimenting with it. Here are the instructions.) Important concepts for-each loop while loop C-style for loop break, continue infinite loop off-by-one error Things to consider (exercises for yourself, not to turn in) What is the purpose of each of the three expressions that appear in the control line of a C-style for loop? The reading mentions three common looping patters that we use in programming: Pattern name Java idiom Java syntax repeat until sentinel while loop while(___) { ... } do n times C-style for loop
  • break
  • Reading
    the instructions.) Important concepts for-each loop while loop C-style for loop break, continue infinite loop off-by-one error Things to consider (exercises for yourself, not to turn in) What is the purpose of each of the three expressions that appear in the control line of a C-style for loop? The reading mentions three common looping patters that we use in programming: Pattern name Java idiom Java syntax repeat until sentinel while loop while(___) { ... } do n times C-style for loop for(___; ___; ___
  • continue
  • Reading
    the instructions.) Important concepts for-each loop while loop C-style for loop break, continue infinite loop off-by-one error Things to consider (exercises for yourself, not to turn in) What is the purpose of each of the three expressions that appear in the control line of a C-style for loop? The reading mentions three common looping patters that we use in programming: Pattern name Java idiom Java syntax repeat until sentinel while loop while(___) { ... } do n times C-style for loop for(___; ___; ___) { ...
  • infinite loop
  • Reading
    Important concepts for-each loop while loop C-style for loop break, continue infinite loop off-by-one error Things to consider (exercises for yourself, not to turn in) What is the purpose of each of the three expressions that appear in the control line of a C-style for loop? The reading mentions three common looping patters that we use in programming: Pattern name Java idiom Java syntax repeat until sentinel while loop while(___) { ... } do n times C-style for loop for(___; ___; ___) { ... }
  • off-by-one error
  • Reading
    Important concepts for-each loop while loop C-style for loop break, continue infinite loop off-by-one error Things to consider (exercises for yourself, not to turn in) What is the purpose of each of the three expressions that appear in the control line of a C-style for loop? The reading mentions three common looping patters that we use in programming: Pattern name Java idiom Java syntax repeat until sentinel while loop while(___) { ... } do n times C-style for loop for(___; ___; ___) { ... } for each element
  • refactoring
  • Practice thinking about and dealing with edge cases and special cases Refactoring In software development, refactoring means changing the structure of code without changing its functionality. On long-running projects, developers often refactor code to keep it readable, maintainable, and ready for the future. But why? Why change code that already works, so that it does exactly the same thing?! There are at least three good reasons for this: to reflect on and improve our own work after completing a first working draft, to make the code clearer to people reading it in the future, and
  • Take-home exercise
    The self-evaluation rubric for this assignment is in SELF_EVALUATION.md. Step 0: Plan Refactoring (n, v): changing the structure of code without changing its functionality. In this activity you will start with some code that works, but is just a bit messy. You will introduce an interface to clean up the code. The code is the start of the battle system for an RPG. Characters can battle each other with dwarven swords and magic fireballs. Here are the rules: Each character in the game has a name, hit points, and energy. “Hit points” refers to how much life the character has left; when hit points reach zero, the character is defeated.
  • edge case
  • When there is some limit or boundary to data — an empty list, an empty string, a minimum value, a maximum value — we refer to the situations where we are working near that boundary as edge cases. When writing tests, it is always important to think about these edge cases. Why? Because bugs tend to live there. For this problem, we can write simple code that works just great when there are 2 elements in the list, or 10, or 100, or 1000000…but doesn’t work for 1 or 0. It’s the edge cases that get us! Now, fix the edge cases of 0 and 1 elements. To do this, you will probably need to treat them as special cases: instead of handling them with the normal logic, you add an if statement that checks for 0 elements and does something special, and another that checks for 1. We don’t generally like special cases in code; it’s better to limit how many paths the code can take. Sometimes, however, a special case is the best solution.
  • special case
  • fix the edge cases of 0 and 1 elements. To do this, you will probably need to treat them as special cases: instead of handling them with the normal logic, you add an if statement that checks for 0 elements and does something special, and another that checks for 1. We don’t generally like special cases in code; it’s better to limit how many paths the code can take. Sometimes, however, a special case is the best solution. When the new edge case tests pass, inspect the diff and commit your work. Study the solutions Either now, or after class, or after you do the bonus challenges below:
  • class
  • affect visible properties (“Can the key turn?”) and behaviors (“Try turning the key!”). Class A class is a category of objects with a shared structure, objects that have the same potential states and behaviors. “Door” might be a class. “Table” might be a different class. “Car” might be a different class. (Note that we say “might be.” Deciding how to divide the world of an object-oriented program up into objects and classes is a subjective design decision that never has a single correct answer. Much of the work of programming is making subjective decisions like this: not writing code, but deciding what
  • You should skip sections 6.3.3, 6.3.4, 6.3.5, and 6.3.6 (6.3.3 to the end of the 6.3 subsection), which are concepts that we will not be using in this course. Important concepts class, object state behavior scope encapsulation instance variable (a.k.a member variable, or in Java, field) visibility, access control getter and setter (a.k.a. accessor and mutator) Things to consider (exercises for yourself, not to turn in) Every class defines a constructor method (possibly implicitly). What is the purpose of a constructor? Assume you are given code for a class called “Button” that represents a button on your screen. The Button constructor method takes four parameters: double xPosition, double yPosition, double width, double height. Write a single line of code to create a Button variable and initialize it at position (100, 200) with a width of 30 and a height of 20.
  • object
  • group together the behaviors and the state that are connected. Objects and Classes Object An object is one thing whose state and behavior are tightly interconnected. In the example above, the door that connects our classroom to the hallway is one door object. The doors that leads directly into the neighboring classrooms are two different door object. Each one of the doors at the top of the front steps of OLRI is a different door object. An object can have properties (also known as attributes) that describe its state. The properties of a door, for example, might be “hinge angle“ and “color”, and the
  • You should skip sections 6.3.3, 6.3.4, 6.3.5, and 6.3.6 (6.3.3 to the end of the 6.3 subsection), which are concepts that we will not be using in this course. Important concepts class, object state behavior scope encapsulation instance variable (a.k.a member variable, or in Java, field) visibility, access control getter and setter (a.k.a. accessor and mutator) Things to consider (exercises for yourself, not to turn in) Every class defines a constructor method (possibly implicitly). What is the purpose of a constructor? Assume you are given code for a class called “Button” that represents a button on your screen. The Button constructor method takes four parameters: double xPosition, double yPosition, double width, double height. Write a single line of code to create a Button variable and initialize it at position (100, 200) with a width of 30 and a height of 20.
  • state
  • Consider the door example from the first day of class. Here are examples of things that would be part of the state of a particular door: The door is open at a 37° angle. The handle is in the rest position. The door is unlocked. The door is green. The door is not latched. There is a key inserted in the lock. The tiny little pins inside the lock mechanism are raised by 3mm, 1mm, 4mm, etc. You can think of state as “the current characteristics of a thing at a moment in time,” or “what is currently true about a thing,” or (anthropomorphizing a bit) “what a thing knows about itself.”
  • You should skip sections 6.3.3, 6.3.4, 6.3.5, and 6.3.6 (6.3.3 to the end of the 6.3 subsection), which are concepts that we will not be using in this course. Important concepts class, object state behavior scope encapsulation instance variable (a.k.a member variable, or in Java, field) visibility, access control getter and setter (a.k.a. accessor and mutator) Things to consider (exercises for yourself, not to turn in) Every class defines a constructor method (possibly implicitly). What is the purpose of a constructor? Assume you are given code for a class called “Button” that represents a button on your screen. The Button constructor method takes four parameters: double xPosition, double yPosition, double width, double height. Write a single line of code to create a Button variable and initialize it at position (100, 200) with a width of 30 and a height of 20.
  • behavior
  • You can think of state as “the current characteristics of a thing at a moment in time,” or “what is currently true about a thing,” or (anthropomorphizing a bit) “what a thing knows about itself.” Here are examples of behaviors of a door: Open Shut Lock Unlock Turn handle Push Behaviors are actions a thing can do, or have done to it. The first central insight of OOP is that state and behavior are interconnected. How? Behaviors can change state: If you push the door (behavior), then the angle at which it is open (state) can change. If you lock the door (behavior), then the door becomes locked (state). If you paint the door, it can become a different color.
  • You should skip sections 6.3.3, 6.3.4, 6.3.5, and 6.3.6 (6.3.3 to the end of the 6.3 subsection), which are concepts that we will not be using in this course. Important concepts class, object state behavior scope encapsulation instance variable (a.k.a member variable, or in Java, field) visibility, access control getter and setter (a.k.a. accessor and mutator) Things to consider (exercises for yourself, not to turn in) Every class defines a constructor method (possibly implicitly). What is the purpose of a constructor? Assume you are given code for a class called “Button” that represents a button on your screen. The Button constructor method takes four parameters: double xPosition, double yPosition, double width, double height. Write a single line of code to create a Button variable and initialize it at position (100, 200) with a width of 30 and a height of 20.
  • interface
  • A car presents a driver with properties (Is it turned on? How far down is the pedal pushed?) and behaviors (Turn the wheel! Push the pedal! Honk the horn!). Those things that the driver can see and use and do are the interface of the abstraction. A car’s interface has some complexity to it! Driving well is not easy (as many people on the road prove every day). However, the internals of the car are far more complex than its interface. You don’t have to know how a transmission or a motor works to drive a car. These implementation details of a car are hidden from the driver. What is the internal state of the car? A mechanic might have to figure it out, but the driver doesn’t. In fact, the implementation details and internal state of a car are not merely
  • Activity
    . We have words for both sides of that split. The rules for how other code uses the abstraction are its interface or API (application programming interface). The details of how it works are its implementation. Software development mostly consists of understanding abstractions that other people have created for you, and using those abstractions to solve your problem. (Software development also consists of creating your own abstractions as your code grows — but today we’re focusing on using other people’s abstractions.) The syntax and the terminology
  • Reading
    In the Interfaces chapter, read through the end of the section on “The List Interface.” You may stop at “The Map Interface.” Important concepts interface polymorphism Things to consider (exercises for yourself, not to turn in) The reading mentions that an interface is a contract of behavior. What sorts of challenges might come up if you change an interface that has been in use by other software for a while? We have already seen polymorphism in action! Think about or take a look at the kilt-graphics documentation again. Where can you find an example of polymorphism? (Hint: there are a few options!)
  • Activity
    Remember from the reading: when creating an interface, you do not provide an actual implementation of the method. Put a semicolon after the method signature. Congratulations! You have an interface. An interface in Java is a description of something that multiple different classes have in common. In this case, what we are saying is, “There is something called Media in our world. Many different classes could all be kinds of Media. What they all have in common are that they have titles, and you can check them out and check them in.” Java syntax What it’s called What it means interface Media { } interface declaration
  • Freeman, Eric, and Elisabeth Robson. Head First Design Patterns. 2nd ed., O’Reilly, 2020. Important concepts interfaces and inheritance unintended consequences of code change encapsulating the parts that vary, separating them from the parts that don’t classes that represent behaviors instead of things Things to consider (exercises for yourself, not to turn in) Which activities and assignments in this course exemplify the advice in this chapter? Why does the reading say not to create a “Duck” interface too? If a programming tool matters, it’s because it solves a problem. What problem do interfaces solve?
  • instantiate
  • instantiation
  • of a class. For example, our classroom’s door is an instance of the “door” class. When we make a new object of a certain class, we call it instantiating the class. To add a new door to a room, you’d need to “instantiate the door class.” Class Definition We said above that all the objects of a certain class have a shared structure. What does this mean? It means that all the various objects of a given class all have the same behaviors, the same potential states, and the same properties. For example: some doors are open and some doors are shut (different states), but they all could be open or shut (
  • Activity
    . This variable could point to any object that is a Cat. It doesn’t point to any object yet, but it could!” new Cat() object instantiation (n) instantiate a Cat object (v) “Create a new object that is a Cat. The object didn’t exist before; now it does. No variable points to it…yet.” felix = …; assignment (n) assign … to felix (v) “Make the felix variable point to whatever the expression on the right-hand side gives us. The declaration of felix above says the variable can only reference Cat objects, so please make sure that expression is guaranteed to give us a
  • property
  • attribute
  • door object. Each one of the doors at the top of the front steps of OLRI is a different door object. An object can have properties (also known as attributes) that describe its state. The properties of a door, for example, might be “hinge angle“ and “color”, and the values of those properties might be “37°” and “green.” An object can have internal state that is not a visible property, such as the position of all the little pins in the lock mechanism of a door. Note that although the lock pins are not visible, they do affect visible properties (“Can the key turn?”) and behaviors (“Try turning the key!”).
  • Activity
    (some would say annoyingly!) common pattern in Java. People sometimes refer to the instance variable + getter + setter all together as a property of the class. The autocomplete feature you used is very helpful for writing getters and setters — but remember what the String Methods activity had to say about never letting the computer do the thinking for you! Do use autocomplete for boilerplate code like this. Java in particular has a verbose syntax designed with the assumption you will lean on autocomplete. Do not stop paying attention to what the autocomplete generates, or what it means, or how the pieces of it fit together.
  • internal state
  • ) that describe its state. The properties of a door, for example, might be “hinge angle“ and “color”, and the values of those properties might be “37°” and “green.” An object can have internal state that is not a visible property, such as the position of all the little pins in the lock mechanism of a door. Note that although the lock pins are not visible, they do affect visible properties (“Can the key turn?”) and behaviors (“Try turning the key!”). Class A class is a category of objects with a shared structure, objects that have the same potential states and behaviors. “Door” might be a class. “Table” might be a different class. “Car” might be a different class.
  • . This reading mentions some concepts we have not covered in class, but you should be able to understand the core points. Important concepts defensive programming invariant malicious client internal state defensive copy Things to consider (exercises for yourself, not to turn in) Think of an example of each of the following: class invariant immutable class non-final class window of vulnerability How do you determine whether an object is immutable? Is an immutable object always “safe?” What if you are writing code that is never called by or used by someone who is not on your team? Would you ever still want to practice “defensive programming” to defend against
  • encapsulation
  • the driver. You shouldn’t be able to rearrange the gears in the transmission or release the toxic chemicals in the battery by operating the interface of the car. If you could, we’d consider this a serious failure! This hiding and protecting of implementation details and internal state is called encapsulation. The third big insight of object-oriented programming is that when we make good decisions about what we encapsulate and what interface we present, it increases our ability to keep software manageable as its complexity grows — even when it grows beyond the point where any one person can understand all of it at once! Software Too! Throughout this reading, we’ve looked at physical objects (doors, cars) as analogies for what software does. Let’s consider an actual piece of software acting as an abstraction:
  • Activity
    previous reading, this separation between how to use an abstraction and how the abstraction works is encapsulation. We have words for both sides of that split. The rules for how other code uses the abstraction are its interface or API (application programming interface). The details of how it works are its implementation. Software development mostly consists of understanding abstractions that other people have created for you, and using those abstractions to solve your problem. (Software development also consists of creating your own abstractions as your code grows — but today we’re focusing on using other people’s abstractions.)
  • You should skip sections 6.3.3, 6.3.4, 6.3.5, and 6.3.6 (6.3.3 to the end of the 6.3 subsection), which are concepts that we will not be using in this course. Important concepts class, object state behavior scope encapsulation instance variable (a.k.a member variable, or in Java, field) visibility, access control getter and setter (a.k.a. accessor and mutator) Things to consider (exercises for yourself, not to turn in) Every class defines a constructor method (possibly implicitly). What is the purpose of a constructor? Assume you are given code for a class called “Button” that represents a button on your screen. The Button constructor method takes four parameters: double xPosition, double yPosition, double width, double height. Write a single line of code to create a Button variable and initialize it at position (100, 200) with a width of 30 and a height of 20.
  • class declaration
  • class definition
  • All the objects of a given class have some shared structure. A description of that shared structure is called a class definition. Based on the discussion above, we might define the “door” class like this: Door class Properties: hinge angle (number, in degrees) is locked? (boolean) color Behaviors: open shut lock unlock (with a key) repaint (with a new color) This class definition is like a blueprint for all door objects. If we have a door, we know that we can try to shut it or unlock it. The door might not allow it, but we can try! However, we can’t try to
  • Activity
    Java syntax What it’s called What it means class Bicycle { … } class declaration (n) declare a class (v) “In our world, Bicycle is one type of thing that can exist. There aren’t any of them yet! But there could be. Here is a description of their state and behavior….” public public access modifier (n) make it public (v) “This thing isn’t hidden from the world; it isn’t encapsulated. It is a part of our public API, and other code can use it.” Task 1: Add a property We are going to add a piece of state to our bicycle:
  • instance
  • There can be many objects of the same class. There are many doors in the world, and they are all doors. We say that an object is an instance of a class. For example, our classroom’s door is an instance of the “door” class. When we make a new object of a certain class, we call it instantiating the class. To add a new door to a room, you’d need to “instantiate the door class.” Class Definition We said above that all the objects of a certain class have a shared structure. What does this mean? It means that all the various objects of a given class all have the same behaviors, the
  • API
  • Activity
    . We have words for both sides of that split. The rules for how other code uses the abstraction are its interface or API (application programming interface). The details of how it works are its implementation. Software development mostly consists of understanding abstractions that other people have created for you, and using those abstractions to solve your problem. (Software development also consists of creating your own abstractions as your code grows — but today we’re focusing on using other people’s abstractions.) The syntax and the terminology In this activity, the code you will read and write does a surprising number of different things with just a few basic building blocks, listed in the table below. Study this table carefully! This syntax and this terminology is
  • Reading
    . (It stands for “application programming interface,” but hardly anybody spells that out, even in formal writing. It’s just “API.”) This is an extremely broad term. Here is a definition: An API is a set of expectations that one piece of code (the “API provider”) fulfills so that other code (“API clients”) can interact with it. Those “expectations” might include: What kind of communication mechanism to use What operations or actions are available, and what their names are What types or data formats those operations will use for input and output What assumptions a client may and may not make about those operations In other words,
  • library
  • Activity
    need the emoji(s) you created for the next take-home exercise! Your partner can clone/pull after you push. Libraries In programming, a library is reusable unit of code that is not a whole program in itself, but is instead designed for many different programs to use. Programmers share libraries with each other, and there are thousands of libraries available online to solve common (or uncommon!) problems. Each library focuses on some particular set of related problems or tasks. There are libraries, for example, for doing statistical analysis and creating animations in video games and generating music. One example of a library you are already using is JUnit, which focuses on automated testing of code. Including the JUnit library is what lets you write
  • Reading
    allows separate programs on the same computer to share data. The file system is the most familiar example of this: many programs can read and write the same file, because the computer’s operating system provides a common API for all of them to interact with those files. There are other inter-process communication mechanisms too, such as pipes and sockets. You might get a taste of this in COMP 240. A library is independent code meant for other software projects to use directly, not communicating with another computer or another program, but within the same program. For example, Kilt Graphics is a library. The Java Collections Framework that provides List and ArrayList is also a library. Every library provides an API, either explicitly or implicitly. Unlike remote and inter-process APIs, which tend to be language-independent, this kind of API is language-specific: it exposes its capabilities to clients using the features of one particular programming language. For example, a Java library provides…
  • variable declaration
  • Activity
    , in this course and beyond. Java syntax What it’s called What it means Cat felix variable declaration (n) declare felix (v) “Here is a new variable named felix. This variable could point to any object that is a Cat. It doesn’t point to any object yet, but it could!” new Cat() object instantiation (n) instantiate a Cat object (v) “Create a new object that is a Cat. The object didn’t exist before; now it does. No variable points to it…yet.” felix = …; assignment (n) assign … to felix (v) “Make the
  • Activity
    objects, so please make sure that expression is guaranteed to give us a Cat.” Cat felix = new Cat(); variable declaration with an initializer (n) declare and initialize a variable (v) All of the above at once: “Here is a new variable named felix. Create a new object that is a Cat, and make the felix variable point to it.” felix.meow() method call (n) call the meow method of felix (v) “Find whatever object felix currently is pointing to, and ask that object to meow / send it the meow message.” Spot these building blocks in the code, and
  • assignment
  • assign
  • Activity
    . The object didn’t exist before; now it does. No variable points to it…yet.” felix = …; assignment (n) assign … to felix (v) “Make the felix variable point to whatever the expression on the right-hand side gives us. The declaration of felix above says the variable can only reference Cat objects, so please make sure that expression is guaranteed to give us a Cat.” Cat felix = new Cat(); variable declaration with an initializer (n) declare and initialize a variable (v) All of the above at once: “Here is a new variable named
  • initialize
  • initializer
  • Activity
    objects, so please make sure that expression is guaranteed to give us a Cat.” Cat felix = new Cat(); variable declaration with an initializer (n) declare and initialize a variable (v) All of the above at once: “Here is a new variable named felix. Create a new object that is a Cat, and make the felix variable point to it.” felix.meow() method call (n) call the meow method of felix (v) “Find whatever object felix currently is pointing to, and ask that object to meow / send it the meow message.” Spot these building blocks in the code, and
  • call
  • Activity
    , and make the felix variable point to it.” felix.meow() method call (n) call the meow method of felix (v) “Find whatever object felix currently is pointing to, and ask that object to meow / send it the meow message.” Spot these building blocks in the code, and practice using the proper terminology to describe them out loud as you work with your partner: ❌ “Now type ‘Cat felix equals…’” ✅ “Let’s declare a Cat variable named felix, and initialize it to…” The extra words are worth it: they will allow you to communicate better with other developers, construct better web searches for your programming questions, read documentation better, and more easily transfer your object-oriented programming knowledge to new languages.
  • instance variable
  • field
  • member variable
  • Activity
    (We limit the range because a bicycle’s steering doesn’t work properly when we turn the wheel past 90°, and we don’t want to try to model the complex behavior of a bicycle falling over!) To do this, we will add an instance variable named direction with type double. An instance variable is a variable that is attached to an object. Instance variables are what keep track of the state of an object. The variable’s lifecycle begins when the object is created, and ends when the object is no longer used. A class declaration lists the instance variables each object of this class will have. When you create a new object, that object gets its own personal storage for each of the instance variables the class declaration says it should have. In this case, we are going to say that every
  • Activity
    What it’s called What it means class Bicycle { … double direction; … } instance variable (in Java, also known as a field) (n) declare an instance variable (v) “Every Bicycle has a direction. Direction is a part of the state of a bicycle: even when the Bicycle is just sitting there, not doing anything, it still always has a direction. The direction exists as long as the bicycle exists. It is a double-precision floating point number.” Question: What syntax makes direction an instance variable, and not a local variable?
  • You should skip sections 6.3.3, 6.3.4, 6.3.5, and 6.3.6 (6.3.3 to the end of the 6.3 subsection), which are concepts that we will not be using in this course. Important concepts class, object state behavior scope encapsulation instance variable (a.k.a member variable, or in Java, field) visibility, access control getter and setter (a.k.a. accessor and mutator) Things to consider (exercises for yourself, not to turn in) Every class defines a constructor method (possibly implicitly). What is the purpose of a constructor? Assume you are given code for a class called “Button” that represents a button on your screen. The Button constructor method takes four parameters: double xPosition, double yPosition, double width, double height. Write a single line of code to create a Button variable and initialize it at position (100, 200) with a width of 30 and a height of 20.
  • Reading
    Please read sections 6.6-6.9. 6.10 is optional Important concepts local variable, instance variable, static variable / class variable static method / class method dependency is-a vs. has-a The special “this” variable types of testing Things to consider (exercises for yourself, not to turn in) If you program a class and you do not code a constructor, does the class have a constructor? (OK, this one is from the tail end of 5.4 on last reading, but it’s good to revisit.) Describe in your own words the difference between static (class) and non-static (instance) methods.
  • getter
  • accessor
  • getter method
  • Activity
    a part of our public API, and outside code cannot see it or use it directly. If other code wants to know about it or change it, it will need to ask via some behavior that is part of our API.” double getDirection() getter / getter method (n) declare a getter (v) “If you want to know about the direction of a bicycle, you have to ask. The bicycle code gets to decide what it reveals to you about its direction.” void setDirection(double direction) setter / setter method (n) declare a setter (v) “If you want to change the direction of a bicycle, you have to ask. The bicycle gets to decide what happens when you try to change the direction. It may or may not honor your request.”
  • instance variable (a.k.a member variable, or in Java, field) visibility, access control getter and setter (a.k.a. accessor and mutator) Things to consider (exercises for yourself, not to turn in) Every class defines a constructor method (possibly implicitly). What is the purpose of a constructor? Assume you are given code for a class called “Button” that represents a button on your screen. The Button constructor method takes four parameters: double xPosition, double yPosition, double width, double height. Write a single line of code to create a Button variable and initialize it at position (100, 200) with a width of 30 and a height of 20.
  • setter
  • mutator
  • setter method
  • Activity
    “If you want to know about the direction of a bicycle, you have to ask. The bicycle code gets to decide what it reveals to you about its direction.” void setDirection(double direction) setter / setter method (n) declare a setter (v) “If you want to change the direction of a bicycle, you have to ask. The bicycle gets to decide what happens when you try to change the direction. It may or may not honor your request.” this this (n) (also called self in many languages, e.g. Python, Swift, Ruby) “The object this method belongs to; the particular bicycle that is performing the behavior we are describing here.”
  • instance variable (a.k.a member variable, or in Java, field) visibility, access control getter and setter (a.k.a. accessor and mutator) Things to consider (exercises for yourself, not to turn in) Every class defines a constructor method (possibly implicitly). What is the purpose of a constructor? Assume you are given code for a class called “Button” that represents a button on your screen. The Button constructor method takes four parameters: double xPosition, double yPosition, double width, double height. Write a single line of code to create a Button variable and initialize it at position (100, 200) with a width of 30 and a height of 20.
  • static variable
  • class variable
  • Activity
    Commit and push. Java syntax What it’s called What it means static static variable / static method (n) “There is only one of this thing in our whole world. It belongs to the whole class, not to any particular object.” Alas, the word “static” means several completely different and unrelated things in programming. Sorry! Here we are talking about static variables and static methods. In this context, “static” means “there is just one of it;” it is the opposite of “instance:” static variable → just one of it instance variable → each object has its own
  • Reading
    sections 6.6-6.9. 6.10 is optional Important concepts local variable, instance variable, static variable / class variable static method / class method dependency is-a vs. has-a The special “this” variable types of testing Things to consider (exercises for yourself, not to turn in) If you program a class and you do not code a constructor, does the class have a constructor? (OK, this one is from the tail end of 5.4 on last reading, but it’s good to revisit.) Describe in your own words the difference between static (class) and non-static (instance) methods.
  • this
  • self
  • Activity
    “If you want to change the direction of a bicycle, you have to ask. The bicycle gets to decide what happens when you try to change the direction. It may or may not honor your request.” this this (n) (also called self in many languages, e.g. Python, Swift, Ruby) “The object this method belongs to; the particular bicycle that is performing the behavior we are describing here.” Some languages call this self instead, and that’s a nice way to think of it: “I’m an object providing a behavior, and this is me!” this.direction instance variable access (n) use the instance variable (v) “Maybe there are other local variables named
  • Reading
    class variable static method / class method dependency is-a vs. has-a The special “this” variable types of testing Things to consider (exercises for yourself, not to turn in) If you program a class and you do not code a constructor, does the class have a constructor? (OK, this one is from the tail end of 5.4 on last reading, but it’s good to revisit.) Describe in your own words the difference between static (class) and non-static (instance) methods. In what situations might method overloading be helpful? Your response What was particularly interesting, confusing, or exciting to you in this reading?
  • model
  • Activity
    about a bicycle, and it won’t describe every bicycle in the world. It is a simplified description that captures just a few things that we care about, just accurately enough for our purposes. That is what the word “modeling” means. A model represents something messy and complex with something that is simpler or more abstract. When we use mathematics to model something (for example, equations that describe electromagnetism or plant growth or economic markets), we call it a “mathematical model.” When we use thoughts — metaphors, images, rules, heuristics, etc. — to model something, we call it a “mental model.” Similarly, when we use object-oriented programming to model something, we call it an “
  • object model
  • Activity
    .” Similarly, when we use object-oriented programming to model something, we call it an “object model.” An essential feature of models is that they don’t describe everything. A model has to leave some things out; otherwise it’s not a model. A related saying you may hear is “all models are wrong, but some are useful” (George Box). Your goal is not to reproduce all of reality. Your goal is to make a model that is useful for the problem at hand. Because of this, it is not sufficient to consider only the accuracy of a model; it is equally crucial to ask questions about the
  • package
  • Activity
    ! This is what the course style guide means when it says you should create classes in a package.) VS Code should create a file that says package bicyclemodel; at the top, and that contains an empty class declaration. This starter file combines two different pieces of Java syntax, both important: Java syntax What it’s called What it means class Bicycle { } class declaration (n) declare a class (v) “In our world, Bicycle is one type of thing that can exist. There aren’t any of them yet! But there could be. Here is a description of their state and behavior….”
  • public access modifier
  • Activity
    is one type of thing that can exist. There aren’t any of them yet! But there could be. Here is a description of their state and behavior….” public public access modifier (n) make it public (v) “This thing isn’t hidden from the world; it isn’t encapsulated. It is a part of our public API, and other code can use it.” Task 1: Add a property We are going to add a piece of state to our bicycle: direction: the direction that the bicycle’s steering column is currently pointed. Measured in degrees. Straight ahead is 0°. Always in the range -90°…90°. (We limit the range because a bicycle’s steering doesn’t work properly when we turn the wheel past 90°, and we don’t want to try to model the complex behavior of a bicycle falling over!)
  • field
  • Activity
    class Bicycle { … double direction; … } instance variable (in Java, also known as a field) (n) declare an instance variable (v) “Every Bicycle has a direction. Direction is a part of the state of a bicycle: even when the Bicycle is just sitting there, not doing anything, it still always has a direction. The direction exists as long as the bicycle exists. It is a double-precision floating point number.” Question: What syntax makes direction an instance variable, and not a local variable? The variable declaration is nested directly inside the class. It is not inside a method.
  • private access modifier
  • Activity
    Then the direction would exist only while that method is running. Every time the method returned, the direction would disappear. Direction would not be part of the state of a bicycle, and every bicycle would not have a direction. private private access modifier (n) make it private (v) “This thing is hidden from the world; it is encapsulated. It is not a part of our public API, and outside code cannot see it or use it directly. If other code wants to know about it or change it, it will need to ask via some behavior that is part of our API.” double getDirection() getter / getter method (n) declare a getter (v) “If you want to know about the direction of a bicycle, you have to ask. The bicycle code gets to decide what it reveals to you about its direction.”
  • constant declaration
  • Activity
    Java syntax What it’s called What it means static final double DRAG constant declaration (n) declare a constant (v) “There is one single DRAG value shared by all bicycles. It is a double. It never changes.” void pedalHarder() { } method declaration (n) declare a method (v) “You can ask a bicycle to pedal harder. That is one of the behaviors of a bicycle.” We’ve already seen method declarations…haven’t we? Well, yes, but this is something new: it does not have the static
  • method declaration
  • Activity
    value shared by all bicycles. It is a double. It never changes.” void pedalHarder() { … } method declaration (n) declare a method (v) “You can ask a bicycle to pedal harder. That is one of the behaviors of a bicycle.” We’ve already seen method declarations…haven’t we? Well, yes, but this is something new: it does not have the static modifier. Because it is not a static method, we are saying that pedaling harder is something that a specific bicycle can do. You can’t just say “for all bicycles in general, pedal harder!” We have to say which
  • static
  • Activity
    Other than changing the name to lowercase, which is only a matter of style, what is the difference here? Two words: static and final. In this context, “static” means “shared by all objects of this class,” and “final” means “can only be assigned to once, i.e. can never change after it’s set.” So if we want to have each bicycle have its own (potentially different) drag? Drop the word static (and make the variable name lowercase). But if we don’t want a particular bike’s drag to ever change? Keep the word final: private final double drag = 0.1; // immutable state Change drag, pedalPower
  • final variable
  • Activity
    and final. In this context, “static” means “shared by all objects of this class,” and “final” means “can only be assigned to once, i.e. can never change after it’s set.” So if we want to have each bicycle have its own (potentially different) drag? Drop the word static (and make the variable name lowercase). But if we don’t want a particular bike’s drag to ever change? Keep the word final: private final double drag = 0.1; // immutable state Change drag, pedalPower, and brakingPower so that they are all immutable state for each individual bicycle.
  • Activity
    context, the word “static” means “before the code runs;” it is the opposite of “runtime.” These really should have been two different words! final double drag final variable (n) “This variable’s value can never change. We are only allowed to assign to it exactly once: no more, no less.” Add a constructor that sets drag OK, so each individual bicycle could have its own unique drag…but we’re still setting them all to 0.1. That isn’t very useful! How do we let different bikes have different drags? We create a constructor that takes drag as a parameter. A constructor is code that runs exactly once when an object is first created. The constructor sets up the initial state of the object — setting instance variables to appropriate values, and possibly other work too — so that the object is ready to use.
  • constructor
  • Activity
    have its own unique drag…but we’re still setting them all to 0.1. That isn’t very useful! How do we let different bikes have different drags? We create a constructor that takes drag as a parameter. A constructor is code that runs exactly once when an object is first created. The constructor sets up the initial state of the object — setting instance variables to appropriate values, and possibly other work too — so that the object is ready to use. To do this: Remove the assignment that initializes drag to 0.1. Java will now (accurately) complain that drag is never initialized. Note that Java complains about this specifically because we declared the variable
  • Activity
    What it’s called What it means class Bicycle { … Bicycle(…) { … } … } constructor (n) declare a constructor (v) “When we create a new bicycle object, here is one of the ways we can set up its initial state so that it is all ready for other code to interact with it.” this(); constructor chaining (n) call another constructor (v) “When somebody calls this constructor here, first call this other constructor over there.” A little reward at the end Find the file named build.gradle inside the project. This is that file that tells Java how your project is set up, where to look for code, etc.
  • Activity
    . This will give you the parts of the train common to all three. Then you can add on the parts that are unique to each of the three types of train car to their respective constructors. This enables you to also add other different kinds of TrainCar classes if you want them — and greatly simplify the TrainDrawer class, which is really bigger than it should be! Recall that a constructor is the setup code that runs exactly once when an object is first created. The technique we will use in this activity where one constructor calls another is called constructor chaining. There is setup that all TrainCars share, and it lives in the TrainCar superclass. The subclasses call that TrainCar constructor first — that is the chaining — and then they do their own additional setup. Refactoring the Existing Code We are going to rearrange the code from the original single
  • constructor chaining
  • Activity
    “When we create a new bicycle object, here is one of the ways we can set up its initial state so that it is all ready for other code to interact with it.” this(…); constructor chaining (n) call another constructor (v) “When somebody calls this constructor here, first call this other constructor over there.” A little reward at the end Find the file named build.gradle inside the project. This is that file that tells Java how your project is set up, where to look for code, etc. Inside that file, find this line: sourceSets.main.java.srcDirs = ['src'] Change it to: sourceSets.main.java.srcDirs
  • Activity
    first created. The technique we will use in this activity where one constructor calls another is called constructor chaining. There is setup that all TrainCars share, and it lives in the TrainCar superclass. The subclasses call that TrainCar constructor first — that is the chaining — and then they do their own additional setup. Refactoring the Existing Code We are going to rearrange the code from the original single TrainDrawer class from the previous activity into several classes, according to our class diagram shown above. The goal is: TrainDrawer should not have to concern itself with any specific train-related logic. It does one thing: it acquires an object with the graphics for a train, and draws that.
  • visibility
  • scope encapsulation instance variable (a.k.a member variable, or in Java, field) visibility, access control getter and setter (a.k.a. accessor and mutator) Things to consider (exercises for yourself, not to turn in) Every class defines a constructor method (possibly implicitly). What is the purpose of a constructor? Assume you are given code for a class called “Button” that represents a button on your screen. The Button constructor method takes four parameters: double xPosition, double yPosition, double width, double height. Write a single line of code to create a Button variable and initialize it at position (100, 200) with a width of 30 and a height of 20.
  • access control
  • encapsulation instance variable (a.k.a member variable, or in Java, field) visibility, access control getter and setter (a.k.a. accessor and mutator) Things to consider (exercises for yourself, not to turn in) Every class defines a constructor method (possibly implicitly). What is the purpose of a constructor? Assume you are given code for a class called “Button” that represents a button on your screen. The Button constructor method takes four parameters: double xPosition, double yPosition, double width, double height. Write a single line of code to create a Button variable and initialize it at position (100, 200) with a width of 30 and a height of 20.
  • GUI
  • graphical user interface
  • You will use the command line for these puzzles! What’s the “command line?” Most of the programs you use have a graphical user interface (GUI). Some programs, however, also have — and many only have — a command line interface (CLI). This is a kind of text-based interface in which you type commands to the computer one line of text at a time (thus the name “command line”), and the computer prints the result as text. To get to the command line in a GUI-based computer, you need to open a program that puts the command line in a window for you. On macOS, this program is called “Terminal.”
  • CLI
  • command line interface
  • graphical user interface (GUI). Some programs, however, also have — and many only have — a command line interface (CLI). This is a kind of text-based interface in which you type commands to the computer one line of text at a time (thus the name “command line”), and the computer prints the result as text. To get to the command line in a GUI-based computer, you need to open a program that puts the command line in a window for you. On macOS, this program is called “Terminal.” On Windows, there are two options, “PowerShell” (the newer one) and “Command Prompt” (the older one).
  • local variable
  • Reading
    Reading Please read sections 6.6-6.9. 6.10 is optional Important concepts local variable, instance variable, static variable / class variable static method / class method dependency is-a vs. has-a The special “this” variable types of testing Things to consider (exercises for yourself, not to turn in) If you program a class and you do not code a constructor, does the class have a constructor? (OK, this one is from the tail end of 5.4 on last reading, but it’s good to revisit.) Describe in your own words the difference between static (class) and non-static (instance) methods.
  • dependency
  • Reading
    , instance variable, static variable / class variable static method / class method dependency is-a vs. has-a The special “this” variable types of testing Things to consider (exercises for yourself, not to turn in) If you program a class and you do not code a constructor, does the class have a constructor? (OK, this one is from the tail end of 5.4 on last reading, but it’s good to revisit.) Describe in your own words the difference between static (class) and non-static (instance) methods. In what situations might method overloading be helpful?
  • is-a
  • is-a relationship
  • Reading
    instance variable, static variable / class variable static method / class method dependency is-a vs. has-a The special “this” variable types of testing Things to consider (exercises for yourself, not to turn in) If you program a class and you do not code a constructor, does the class have a constructor? (OK, this one is from the tail end of 5.4 on last reading, but it’s good to revisit.) Describe in your own words the difference between static (class) and non-static (instance) methods. In what situations might method overloading be helpful?
  • Reading
    of Runestone Java, Java, Java: Object-Oriented Problem Solving, 2024E online book by Morelli et. al. Important concepts subclass, superclass (aka base class) inheritance is-a relationship protected access override class hierarchy abstract class Things to consider (exercises for yourself, not to turn in) Why do we declare most instance variables as private, except when they are instead declared public static final? Would it be better to declare them all protected, just in case a subclass needs them? Or should we use protected only if absolutely necessary? What is the purpose of the special function called super? What happens when code containing a super() call runs?
  • has-a
  • Reading
    static variable / class variable static method / class method dependency is-a vs. has-a The special “this” variable types of testing Things to consider (exercises for yourself, not to turn in) If you program a class and you do not code a constructor, does the class have a constructor? (OK, this one is from the tail end of 5.4 on last reading, but it’s good to revisit.) Describe in your own words the difference between static (class) and non-static (instance) methods. In what situations might method overloading be helpful?
  • separation of concerns
  • Take-home exercise
    cells swim around the screen, and interact with each other. But the whole program is in one big class: the cell, the window, everything, it’s all in one big class: This class violates a principle called separation of concerns: you have one class that is concerned with more than one thing — handling graphics and handling the state of a cell. We want to separate those concerns into distinct classes so that it is easier to work with, understand, and modify the code. You want one simulation with many cells. That’s going to be tricky. In this exercise, you will do the following: Extract a new Cell class, so that the simulation does exactly the same thing — just one cell swimming around — but is now structured in a way that will make the change to many cells relatively easy.
  • In both cases, you start with the same data. The fact that this is possible is because there is a separation of concerns in the code: specific pieces of code have specific responsibilities, and deal only with specific aspects of the problem. In this particular code, some classes are only concerned with what the data is, and others are only concerned with how the data is presented. This particular separation of concerns is called a model / view separation, and presenting the same data in multiple ways is one of its typical purposes. The same approach to model / view separation that lets you show the song song as both graphics and sound might also, for example, let an email app show the same message data in both a concise form in the inbox, and a detailed form for viewing individual messages.
  • stack frame
  • variable pointing to it yet? Also no New terminology This thing you just created is called a stack frame: a container that holds all the local variables of one function / method call. It might look like an object in your physical model, and that is not completely wrong: just like objects hold instance variables, a stack frame holds local variables. The first big difference between the two is their lifecycle. A stack frame appears when a function is called, and vanishes as soon as the function returns. An object appears with the word new
  • aliasing
  • aliased
  • Note that in several places, there are now two variables pointing to the same object. This is called aliasing. Why did this happen in this particular code? Why would you want two different variables to point to the same object? What is that good for? What problems might it cause? Discuss with your team. When the purchase() method calls deduct(), add something separate to represent deduct()’s local variables. (Note that it is critically important that you use two different containers to represent the different methods’ local variables!) With
  • : the object that our main method’s key variable points to is the same object that the map is using as a key. That ArrayList is aliased: two different variables point to the same object. That means that when we run this code: key.add("orange"); …then this happens: Because the HashMap is sharing the same mutable ArrayList object to which we are adding new elements, now the value Nigeria is stored in the map with an incorrect key! (The Nigerian flag 🇳🇬 has no orange.) That is why this document places the words shared mutable state atop flames and chaos above.
  • both point to the same object. (This situation where two variables point to the same object is aliasing, which you may recall if you made it very far in the Idea Lab and Maps activities.) Returning that ArrayList breaks encapsulation! Any code using our API can mess with the internal state of students and courses. This opens the door to insidious bugs. It might even lead to security flaws. A demo and visualization of aliasing Here are two things that will help you see what is happening when one object is aliased to two variables:
  • polymorphism
  • Reading
    In the Interfaces chapter, read through the end of the section on “The List Interface.” You may stop at “The Map Interface.” Important concepts interface polymorphism Things to consider (exercises for yourself, not to turn in) The reading mentions that an interface is a contract of behavior. What sorts of challenges might come up if you change an interface that has been in use by other software for a while? We have already seen polymorphism in action! Think about or take a look at the kilt-graphics documentation again. Where can you find an example of polymorphism? (Hint: there are a few options!)
  • Activity
    — the library contains both! — and depending on which one it is, Java will run a different implementation of checkOut. This magic is called polymorphism. Polymorphism is when one variable in a program can refer to many different types of values, and the same function / method call in the same spot in the code can thus cause different code to run at different times. (Computer scientists quibble about the exact definition of polymorphism and which specific things count, but that is the gist of it.) The word comes from Greek: poly many + morphē form. In our code, polymorphism is what allows the same library code to manage many different kinds of items.
  • override
  • method override
  • Activity
    object is a Media object.” @Override public boolean checkOut() { … } method override annotation (n) (In Java, this @ syntax is called an annotation. @Test is another example.) “I think that this checkOut method matches a method in a supertype. Please give me an error if it doesn’t!” We didn’t ask you to type this, but VS Code might have inserted it for you. It’s a safety check, and a good idea. If, for example, you misspell the method as chekOut, you will get a helpful error message. Did you notice the magic? You might have missed the magic!
  • Reading
    , superclass (aka base class) inheritance is-a relationship protected access override class hierarchy abstract class Things to consider (exercises for yourself, not to turn in) Why do we declare most instance variables as private, except when they are instead declared public static final? Would it be better to declare them all protected, just in case a subclass needs them? Or should we use protected only if absolutely necessary? What is the purpose of the special function called super? What happens when code containing a super() call runs?
  • inherits (reuses) all the instance variables and methods of B, except the ones it chooses to override. Historical background Inheritance is enticing. When programmers first learn about object-oriented programming, it is often inheritance that catches their eye. It feels a little magical (code reuse!). It scratches the deeply human itch to form taxonomies. It offers a tantalizing vision of the overwhelming mess that is code tamed by a tidy inheritance hierarchy, everything in its right place. It is a shiny object that captures our attention. This reaction to inheritance is not unique to college students, or to beginning programmers. OOP was developed in the 1970s
  • interface declaration
  • Activity
    Java syntax What it’s called What it means interface Media { … } interface declaration (n) declare an interface (v) “In our world, Media is one kind of thing that can exist. Many different classes could be a kind of Media.” interface Media { … boolean checkOut(); … } abstract method declaration (n) declare an abstract method (v) “Every class that is a kind of Media must have its out checkOut method that takes no parameters and returns a boolean. We aren’t specifying how that method words; there is no implementation here. We are just saying that this method must exist on any class that is a kind of
  • abstract method
  • Activity
    is one kind of thing that can exist. Many different classes could be a kind of Media.” interface Media { … boolean checkOut(); … } abstract method declaration (n) declare an abstract method (v) “Every class that is a kind of Media must have its out checkOut method that takes no parameters and returns a boolean. We aren’t specifying how that method words; there is no implementation here. We are just saying that this method must exist on any class that is a kind of Media.” This interface directly answers each of the vexing questions questions above: How do we have different fields for different items??
  • supertype
  • Activity
    What it’s called What it means class Book implements Media { … } Media is a supertype of Book Book is a subtype of Media Book is a kind of Media. Every Book object is a Media object.” @Override public boolean checkOut() { … } method override annotation (n) (In Java, this @ syntax is called an annotation. @Test is another example.) “I think that this checkOut method matches a method in a supertype. Please give me an error if it doesn’t!” We didn’t ask you to type this, but VS Code
  • subtype
  • Activity
    class Book implements Media { … } Media is a supertype of Book Book is a subtype of Media Book is a kind of Media. Every Book object is a Media object.” @Override public boolean checkOut() { … } method override annotation (n) (In Java, this @ syntax is called an annotation. @Test is another example.) “I think that this checkOut method matches a method in a supertype. Please give me an error if it doesn’t!” We didn’t ask you to type this, but VS Code might have inserted it for you. It’s a safety check, and a good idea. If, for example, you misspell the method as
  • annotation
  • Activity
    public boolean checkOut() { … } method override annotation (n) (In Java, this @ syntax is called an annotation. @Test is another example.) “I think that this checkOut method matches a method in a supertype. Please give me an error if it doesn’t!” We didn’t ask you to type this, but VS Code might have inserted it for you. It’s a safety check, and a good idea. If, for example, you misspell the method as chekOut, you will get a helpful error message. Did you notice the magic? You might have missed the magic! Your LibraryMain
  • subclass
  • Reading
    of Runestone Java, Java, Java: Object-Oriented Problem Solving, 2024E online book by Morelli et. al. Important concepts subclass, superclass (aka base class) inheritance is-a relationship protected access override class hierarchy abstract class Things to consider (exercises for yourself, not to turn in) Why do we declare most instance variables as private, except when they are instead declared public static final? Would it be better to declare them all protected, just in case a subclass needs them? Or should we use protected only if absolutely necessary?
  • superclass
  • parent class
  • Reading
    of Runestone Java, Java, Java: Object-Oriented Problem Solving, 2024E online book by Morelli et. al. Important concepts subclass, superclass (aka base class) inheritance is-a relationship protected access override class hierarchy abstract class Things to consider (exercises for yourself, not to turn in) Why do we declare most instance variables as private, except when they are instead declared public static final? Would it be better to declare them all protected, just in case a subclass needs them? Or should we use protected only if absolutely necessary?
  • Activity
    , whose constructor contains the code that you reused to make each part of a car the same. A class like this is called a superclass or a parent class for the three other child classes, Engine, Boxcar, and Caboose, which you will also make. Here is a detailed (perhaps too detailed!) diagram of their relationship: The constructor for each of the three child classes will first call the constructor for its parent, TrainCar. This will give you the parts of the train common to all three. Then you can add on the parts that are unique to each of the three types of train car to their respective constructors. This enables you to also add other different kinds of TrainCar classes if you want them — and greatly simplify the TrainDrawer class, which is really bigger than it should be!
  • base class
  • Reading
    of Runestone Java, Java, Java: Object-Oriented Problem Solving, 2024E online book by Morelli et. al. Important concepts subclass, superclass (aka base class) inheritance is-a relationship protected access override class hierarchy abstract class Things to consider (exercises for yourself, not to turn in) Why do we declare most instance variables as private, except when they are instead declared public static final? Would it be better to declare them all protected, just in case a subclass needs them? Or should we use protected only if absolutely necessary? What is the purpose of the special function called super? What happens when code containing a super() call runs?
  • inheritance
  • Reading
    of Runestone Java, Java, Java: Object-Oriented Problem Solving, 2024E online book by Morelli et. al. Important concepts subclass, superclass (aka base class) inheritance is-a relationship protected access override class hierarchy abstract class Things to consider (exercises for yourself, not to turn in) Why do we declare most instance variables as private, except when they are instead declared public static final? Would it be better to declare them all protected, just in case a subclass needs them? Or should we use protected only if absolutely necessary? What is the purpose of the special function called super? What happens when code containing a super() call runs?
  • Head First Design Patterns. 2nd ed., O’Reilly, 2020. Important concepts interfaces and inheritance unintended consequences of code change encapsulating the parts that vary, separating them from the parts that don’t classes that represent behaviors instead of things Things to consider (exercises for yourself, not to turn in) Which activities and assignments in this course exemplify the advice in this chapter? Why does the reading say not to create a “Duck” interface too? If a programming tool matters, it’s because it solves a problem. What problem do interfaces solve?
  • But this specific problem is fixable, right? So…I guess we should just never use inheritance, then? Footnotes Inheritance means two things together: an is-a relationship and code reuse. When class A extends, or inherits from, class B, then: every A is a B, and A inherits (reuses) all the instance variables and methods of B, except the ones it chooses to override. Historical background Inheritance is enticing. When programmers first learn about object-oriented programming, it is often inheritance that catches their eye. It feels a little magical (code reuse!). It scratches the deeply human itch to form taxonomies. It offers a tantalizing vision of the overwhelming mess that is code tamed by a tidy inheritance hierarchy, everything in its right place. It is a shiny object that captures our attention.
  • protected access
  • Reading
    Important concepts subclass, superclass (aka base class) inheritance is-a relationship protected access override class hierarchy abstract class Things to consider (exercises for yourself, not to turn in) Why do we declare most instance variables as private, except when they are instead declared public static final? Would it be better to declare them all protected, just in case a subclass needs them? Or should we use protected only if absolutely necessary? What is the purpose of the special function called super? What happens when code containing a super() call runs?
  • class hierarchy
  • Reading
    superclass (aka base class) inheritance is-a relationship protected access override class hierarchy abstract class Things to consider (exercises for yourself, not to turn in) Why do we declare most instance variables as private, except when they are instead declared public static final? Would it be better to declare them all protected, just in case a subclass needs them? Or should we use protected only if absolutely necessary? What is the purpose of the special function called super? What happens when code containing a super() call runs?
  • abstract class
  • Reading
    base class) inheritance is-a relationship protected access override class hierarchy abstract class Things to consider (exercises for yourself, not to turn in) Why do we declare most instance variables as private, except when they are instead declared public static final? Would it be better to declare them all protected, just in case a subclass needs them? Or should we use protected only if absolutely necessary? What is the purpose of the special function called super? What happens when code containing a super() call runs?
  • composition
  • we model this, then? As with most places where inheritance goes awry, the solution is to replace inheritance with composition: a has-a relationship between objects. The RPG Battle exercise you’re working on (You’ve started, right?) is an excellent example of how to handle this. In that exercise, instead of introducing inheritance to customize something, you introduce a has-a relationship. When you work on that exercise, note that you could repeat the same technique to add more axes of customization to GameCharacter (different defenses and different movement rules, for example), and it would work just fine.
  • Liskov Substitution Principle
  • LSP
  • We just ran face first into one of the fundamental principles of object modeling, named for its inventor, Barbara Liskov3: Liskov Substitution Principle (LSP for short) Every important property of some type should be true of all its subtypes, so that if S is a subtype of T, then it should work to substitute a value of type S in a context that expects a value of type T. (There are more formal ways to state LSP, but this loose description is true to the spirit.) In our case, if Rectangle extends Square, then we should be able to substitute a Rectangle object in any code that expects a
  • forwarding
  • customization by subclassing breaking encapsulation And if you read the optional Effective Java reading: forwarding wrapper class Things to consider (exercises for yourself, not to turn in) What does it mean for a class B to be a subtype of class A? What are some strategies you can imagine to determine whether every instance of B is really an A? What happens when you override a method inherited from a superclass? Could you trace a series of method calls made be a subclass B which inherits from and overrides methods in superclass A? Your response
  • wrapper class
  • breaking encapsulation And if you read the optional Effective Java reading: forwarding wrapper class Things to consider (exercises for yourself, not to turn in) What does it mean for a class B to be a subtype of class A? What are some strategies you can imagine to determine whether every instance of B is really an A? What happens when you override a method inherited from a superclass? Could you trace a series of method calls made be a subclass B which inherits from and overrides methods in superclass A? Your response What was particularly interesting, confusing, or exciting to you in this reading?
  • code smell
  • to do the default “lab and supply closet” check and then also check for the office permission, but this feels like it’s about to get messy as we add more employee types. Hmm, what’s that smell? A code smell is “any characteristic of source code that hints at a deeper problem” (Wikipedia). This is a subjective thing, and it is not a certainty; it is a feeling rooted in experience. The analogy to “smell” is a good one: not all smells are bad, but most of the time, most things shouldn’t smell too much. If there’s a smell, you want to know where it’s coming from. There are two code smells that showed up as we thought through implementation of these new features:
  • final method
  • What it’s called What it means public final boolean hasAccess(Room room) final method (n) “Subclasses may not override this method.” Note that you have also seen final variables. The meaning is completely different; Java just chose to use the same word for both. A final variable cannot have its value changed after it is initialized. A final method prohibits subclassing. Now that those methods are final, we know that we don’t have any inheritance sneaking in to make them work. If they work, they must
  • closure
  • lambda
  • . This reading mentions some concepts we have not covered in class (such as ActionListener, Comparator), but you should be able to understand the core points. Important concepts closure (a.k.a. lambda) variable capture Java closure syntax variants comparator Things to consider (exercises for yourself, not to turn in) What is the difference between a lambda expression and a method? What is a functional interface? How is it connected to lambda expressions? How could you change the code at the bottom of page 323 to make it legal, but still use the value of the variable i in the lambda? Your response
  • show() to add a few simple one-line functions of your own. The parameter to show() is a lambda, also known as a closure. A closure is a piece of code that can be passed around as a value and run in the future — possibly multiple times, possibly not at all! Usually if you said x * x, then Java would immediately look for a variable called x and try to do the multiplication. But here, you are passing that calculation to the graphic calculator and letting it decide whether and when to run it, and what value to provide for x. Note that the whole closure
  • variable capture
  • . This reading mentions some concepts we have not covered in class (such as ActionListener, Comparator), but you should be able to understand the core points. Important concepts closure (a.k.a. lambda) variable capture Java closure syntax variants comparator Things to consider (exercises for yourself, not to turn in) What is the difference between a lambda expression and a method? What is a functional interface? How is it connected to lambda expressions? How could you change the code at the bottom of page 323 to make it legal, but still use the value of the variable i in the lambda? Your response What was particularly interesting, confusing, or exciting to you in this reading?
  • comparator
  • Important concepts closure (a.k.a. lambda) variable capture Java closure syntax variants comparator Things to consider (exercises for yourself, not to turn in) What is the difference between a lambda expression and a method? What is a functional interface? How is it connected to lambda expressions? How could you change the code at the bottom of page 323 to make it legal, but still use the value of the variable i in the lambda? Your response What was particularly interesting, confusing, or exciting to you in this reading?
  • capture
  • variable capture
  • , but also n: int n = 3; calc.show((x, t) -> Math.sin(n * x - t * 10) / n); This is called variable capture. We say that the lambda has “captured n”. A lambda can use this to tie its own logic to its surrounding context. This turns out to be quite powerful, as we will see later this week. There is, however, a catch: in Java, a captured variable must be “effectively final,” which means that it is only assigned to once. Suppose, for example, that we wanted to take the previous function and add it to the calculator many times for different values of
  • event
  • You should open up and read the pages for each of the classes and interafaces! Important concepts event event handler Things to consider (exercises for yourself, not to turn in) Which of the classes in this package are functional interfaces? Which graphics classes have methods that accept these functional interfaces? What are the properties of each type of event? How do they differ? Can you describe, in plain language, what user action would trigger these events, and what the corresponding property values would be? Your response
  • object, which the closure can do because it captures the implicit this variable. The closure thus serves to tie an event from the outside world — in this case, a button click — back to this code’s local world. A closure or function that runs whenever an event occurs is called an event handler or event callback. Add code to make the zoomOut button work too. Test it and make sure it works. (Should you add the button event handlers before or after the call to canvas.animate()? Does it make any difference? Nope! Why? Discuss with your partner. If you’re not sure, try adding some print statements before, inside, and after the event handler closures, and study the order in which the print statements actually happen.
  • event handler
  • event callback
  • You should open up and read the pages for each of the classes and interafaces! Important concepts event event handler Things to consider (exercises for yourself, not to turn in) Which of the classes in this package are functional interfaces? Which graphics classes have methods that accept these functional interfaces? What are the properties of each type of event? How do they differ? Can you describe, in plain language, what user action would trigger these events, and what the corresponding property values would be? Your response What was particularly interesting, confusing, or exciting to you in this reading?
  • from the outside world — in this case, a button click — back to this code’s local world. A closure or function that runs whenever an event occurs is called an event handler or event callback. Add code to make the zoomOut button work too. Test it and make sure it works. (Should you add the button event handlers before or after the call to canvas.animate()? Does it make any difference? Nope! Why? Discuss with your partner. If you’re not sure, try adding some print statements before, inside, and after the event handler closures, and study the order in which the print statements actually happen.) Mouse events Temporarily comment out the whole call to
  • event object
  • . (You can look at that class’s API in your IDE, or in the kilt-graphics javadoc.) Event handlers often receive event objects that describe the event that caused the handler to be called. Run the code and try it! You should be able to manually animate the plot by dragging the mouse back and forth. Dealing with coordinates Note that we are using the absolute x position, which means that the animation parameter jumps suddenly to wherever you start dragging. Try dragging the plot all the way to the right, releasing the mouse button, moving the mouse all the way to the left, and then dragging again. Note the sudden jump when you start dragging again.
  • map (functional operation)
  • Modern Java in Action, Chapter 4: “Introducing Streams” (from “Modern Java in Action” by Urma, Fusco, and Mycroft) Important concepts the map and filter intermediate pipeline operations ← this is the main thing to learn here internal iteration pipelining intermediate operations versus terminal operations on a pipeline Instructor note This reading uses the term “declarative programming” to describe Java stream. I would quibble with that terminology. To be truly “declarative,” code must describe only what results it should produce, and nothing about how to get them. While Java streams do have
  • filter
  • (from “Modern Java in Action” by Urma, Fusco, and Mycroft) Important concepts the map and filter intermediate pipeline operations ← this is the main thing to learn here internal iteration pipelining intermediate operations versus terminal operations on a pipeline Instructor note This reading uses the term “declarative programming” to describe Java stream. I would quibble with that terminology. To be truly “declarative,” code must describe only what results it should produce, and nothing about how to get them. While Java streams do have some
  • intermediate operations
  • intermediate pipeline operations ← this is the main thing to learn here internal iteration pipelining intermediate operations versus terminal operations on a pipeline Instructor note This reading uses the term “declarative programming” to describe Java stream. I would quibble with that terminology. To be truly “declarative,” code must describe only what results it should produce, and nothing about how to get them. While Java streams do have some of this flavor — one might be able to argue that they have a “more declarative style than loops” — Java code that uses streams still does describe a specific algorithm. A truly declarative language, like SQL or Prolog, says nothing about how the computer gets the result.
  • terminal operations
  • intermediate pipeline operations ← this is the main thing to learn here internal iteration pipelining intermediate operations versus terminal operations on a pipeline Instructor note This reading uses the term “declarative programming” to describe Java stream. I would quibble with that terminology. To be truly “declarative,” code must describe only what results it should produce, and nothing about how to get them. While Java streams do have some of this flavor — one might be able to argue that they have a “more declarative style than loops” — Java code that uses streams still does describe a specific algorithm. A truly declarative language, like SQL or Prolog, says nothing about how the computer gets the result.
  • take in a stream, transform it somehow, and return another stream. But at some point you’ve got to stop, right? That’s what terminal operations do. They, uh, terminate the stream and return…well, different kinds of things. There’s two broad categories for what you can do to terminate a stream and do something with all its elements: You can collect them together somehow into some data structure that isn’t a stream. You can do some computation on them and return different kinds of things. The most common thing here is to count them, or calculate some kind of statistical measure. Collecting all the elements of a stream: collections and collectors
  • tradeoff
  • Homework
    — but doing all the math yourself means you have to do all the math yourself! Software development is full of these sorts of tradeoffs: no matter what you choose, you gain something and lose something. There is no single correct answer. It’s all tradeoffs. You need to decide for yourself which approach you want to take. Checkpoints and due dates This homework will have three milestones, each with its own due date: Checkpoint 1, due format_date(data.assignments.hw.breakout_checkpoint_1.due_date) : Plan your implementation by drawing a class diagram
  • collectors
  • Stream terminal operations Important Concepts Two kinds of terminal operations on streams: collectors and reducers. The distinction between three similar-sounding things: Collection (interface for a family of data structures, includes List) Collector (interface for operations that turn streams into collections) collect() (method of Stream) Things to Consider What are two differences between collections and streams? What is the role of a terminal operation in a stream? When you do want to use a collector to terminate a stream? When would you want to use a reducer?
  • reducers
  • Stream terminal operations Important Concepts Two kinds of terminal operations on streams: collectors and reducers. The distinction between three similar-sounding things: Collection (interface for a family of data structures, includes List) Collector (interface for operations that turn streams into collections) collect() (method of Stream) Things to Consider What are two differences between collections and streams? What is the role of a terminal operation in a stream? When you do want to use a collector to terminate a stream? When would you want to use a reducer?
  • Map (data structure)
  • associative array
  • dictionary
  • The output is: {0=[0, 3, 6, 9], 1=[1, 4, 7], 2=[2, 5, 8]} This is what Java calls a Map. We’ll see more on Maps later; for now, just observe what we’re doing: we have various remainders from division by 3, and we want to map them — or associate them with — lists of numbers associated with that remainder. The remainders are called the keys of the Map; the lists are the values associated with those keys. Above, the 0, 1, and 2 on the left side of the equals are the keys; the lists on the right side of the equals are the values. For example, the list
  • You do not need to do the programming exercises in the reading, but you may find it helpful to try them a little. It’s up to you. Important concepts Map data structure (also called a dictionary or associative array in other languages) keys vs values, key-value pair Things to consider (exercises for yourself, not to turn in) The Java Map interface has the get() method for looking up the value that corresponds to a given key. Why isn’t there a method that goes in the other direction, i.e. looking up the key that corresponds to a given value? Is there a situation where containsKey(x) could return
  • in a map, and learn to iterate through each in Java Practice the general skill of learning and working with a library’s API Maps Maps pair keys with values. Keys are unique: if a key is present, it has exactly one value. Values are not necessarily unique: multiple keys could have the same value. In this activity, you will learn how to perform common operations with the Map API. Map is an interface (like List), and the most common implementation of Map is HashMap. Thus, if you are creating a map from Student ids (Integers) to Student objects, you would declare and initialize the map using the following:
  • collection
  • A brief review of collections In English, what is a collection? One reasonable description: A collection is a group or set of things. And what can you do with a collection? What are some of the actions you could perform on a collection? Some examples include: getting the size of the collection; adding, removing things from the collection; asking if the collection contains a certain thing; seeing all the things in the collection Let’s translate that to Java: a collection sounds like an instance of a class. Class instances have state and behavior. Here:
  • collector
  • : a stream is a set of values spread out in time; a collection is a set of values spread out in space. A collector is something that gathers the elements from a stream into a collection. The Collector interface describes such an operation, specifying how the collector accumulates and combines elements, and specifying what kind of collection it produces. From above, if you have a stream, perhaps the most basic way you’d like to collect those spread-out-in-time elements is to put them into a List. Another operation you might want to do with the stream is to group the elements according to some characteristic,
  • reduction
  • Perhaps we don’t want to collect together all the elements of a stream, but instead transform them into…something else. This kind of terminal operation is called reduction. Here are two such reducers. Counting the number of elements in a stream How many numbers less than 100 are prime? This example… Creates the same kind of infinite stream of numbers we’ve been using, then… limits to the first 100 elements of the stream, then… filters out non-prime numbers (equivalently, only allows through those numbers for which the predicate isPrime is true), then… counts the number of elements in the resulting, filtered-to-just-primes stream.
  • concurrency
  • What went wrong? How do we fix it?! Lessons from this adventure Onward In software, concurrency is when multiple tasks have overlapping timespans. Concurrent execution is the opposite of sequential execution. When code runs sequentially, one task finishes completely before the next task starts. You are already used to sequential execution: when you write code, each statement finishes its work before the next statement starts. If you put a loop in your code, the program waits for the loop to finish before moving on to the next thing. If you call a function, the program waits for the function to finish before moving on to the next thing. Code in Java (and Python, and most other common programming languages) is fundamentally sequential.
  • . Continue working with the same partner(s). No need to accept a new assignment, or to clone anything new. Please work from the same repository as before. Recall that concurrency is when multiple tasks happen during overlapping timespans. When code runs concurrently, one task or operation starts before others are finished. How does that work? And why would you do it? In Part 1, we looked at introducing parallel execution in order to make code faster. In Part 2, we will look at a different kind of concurrency that solves a different problem. (This activity uses the same repository as part 1.) Cell Absorption Redux Run the main method of
  • concurrent execution
  • Onward In software, concurrency is when multiple tasks have overlapping timespans. Concurrent execution is the opposite of sequential execution. When code runs sequentially, one task finishes completely before the next task starts. You are already used to sequential execution: when you write code, each statement finishes its work before the next statement starts. If you put a loop in your code, the program waits for the loop to finish before moving on to the next thing. If you call a function, the program waits for the function to finish before moving on to the next thing. Code in Java (and Python, and most other common programming languages) is fundamentally sequential.
  • sequential execution
  • is when multiple tasks have overlapping timespans. Concurrent execution is the opposite of sequential execution. When code runs sequentially, one task finishes completely before the next task starts. You are already used to sequential execution: when you write code, each statement finishes its work before the next statement starts. If you put a loop in your code, the program waits for the loop to finish before moving on to the next thing. If you call a function, the program waits for the function to finish before moving on to the next thing. Code in Java (and Python, and most other common programming languages) is fundamentally sequential.
  • parallelism
  • parallel execution
  • Did you know that most modern computers, probably including your computer, can do multiple things simultaneously? This is called parallel execution, or just parallelism. “Parallel” doesn’t just mean different tasks taking turns while they work; it means different tasks happening at the same time. (When you hear computer advertisements talking about a “4 core processor! 8 core processor! etc,” this is the thing they’re referring to: how many things the computer can do truly simultaneously.) Java streams have an amazing feature: you can tell them to run in parallel! And it only takes only one line of code:
  • race condition
  • Add 1 to 999 → 1000   Write 1000 → total …and then we get the wrong answer. This is called a race condition: the correctness of a computation depends on the exact timing of concurrent tasks. The two workers here are in a data race, each one racing to write its result back to total before the other can read it. The fundamental source of trouble here is that even though there are multiple parallel workers, they are all sharing the same instance variable of the same SumCalculator object: private long total; The term for this is shared mutable state: “shared” because multiple things all use it, “mutable” because it changes. Shared mutable state is a common source of bugs in many situations. When parallelism is present, it can be deadly.
  • data race
  • : the correctness of a computation depends on the exact timing of concurrent tasks. The two workers here are in a data race, each one racing to write its result back to total before the other can read it. The fundamental source of trouble here is that even though there are multiple parallel workers, they are all sharing the same instance variable of the same SumCalculator object: private long total; The term for this is shared mutable state: “shared” because multiple things all use it, “mutable” because it changes. Shared mutable state is a common source of bugs in many situations. When parallelism is present, it can be deadly.
  • shared mutable state
  • instance variable of the same SumCalculator object: private long total; The term for this is shared mutable state: “shared” because multiple things all use it, “mutable” because it changes. Shared mutable state is a common source of bugs in many situations. When parallelism is present, it can be deadly. On effectively final variables, lambdas, closures, and race conditions Were you confused by the “effectively final” concept when you learned about lambdas / closures in Graphic Calculator? One of the reasons the Java language designers created that concept is because of race conditions.
  • thread-safe
  • class is the source of our trouble. It isn’t built for parallelism. (The term people often use for this is that it “isn’t thread-safe.” In this context, “thread” is a term for the abstraction the computer uses to manage parallelism, and even simulate it on single-core computers.) Fortunately, we don’t need SumCalculator at all: Java already provides a sum method for streams. And unlike the SumCalculator class, it knows how to handle parallelism: Timer.measure(20, () -> { long total = LongStream.range(0, 1000000000L) .parallel() .map(n -> 1)
  • cooperative concurrency
  • cooperative multitasking
  • , because other tasks happen during the (endless) timespan of the “animation” task. This approach is called cooperative concurrency, or cooperative multitasking. The particular cooperative concurrency approach that user interface libraries like Kilt Graphics use is called an event loop. There is in fact an infinite loop buried deep in the guts of some library, but you never see it! That loop basically looks like this: while (program is running) { wait until there are events to handle get next event call whatever code handles that event, and wait for it to finish draw new graphics on the screen if necessary }
  • event loop
  • The particular cooperative concurrency approach that user interface libraries like Kilt Graphics use is called an event loop. There is in fact an infinite loop buried deep in the guts of some library, but you never see it! That loop basically looks like this: while (program is running) { wait until there are events to handle get next event call whatever code handles that event, and wait for it to finish draw new graphics on the screen if necessary } The details are more complicated, but the basic idea is as simple as that. Aside: This pattern extends far beyond Kilt Graphics and Java. Almost every GUI platform in the world has an event loop of some kind: HTML+JS in a web browser, iOS / macOS UIKit and SwiftUI, Android and Android Compose, Windows WinUI and .NET and MFC, the Unity and Godot game engines…you name it. Even some server frameworks (like Node/Express) and entire programming languages (like Erlang and Elixir) use an event loop pattern or something like it.
  • array
  • Reading
    Please read sections 7.1–7.3 of the Introduction to Programming with Java. Important concepts array bounds checking Instructor note In the grand tradition of computer science, the terminology here is confusing. The terms “array,” “list,” “vector,” and “tuple” can all means “an ordered sequence of items indexed by number.” These terms appear across many languages, but their semantics varies a great deal from language to language. For example, for something called an “array”, one language may or may not allow changing the size; it may or may not allow you to change the values stored. But another language may work differently for “array”.
  • Activity
    to finish it! This section is review if you did the reading. Give it a quick read, keep it for reference, and get started ASAP. An array is a data type which holds elements arranged by index. In Java, unlike Collection subtypes (e.g. List, Set), an array can hold primitive data types without needing an object wrapper class. This makes arrays the preferred way to store large quantities of numerical data in Java. Huh? What does that mean?? What’s an “object wrapper class?“ (Read this after class if you want to learn more) For example, you can have an int[] (int array) in Java, but you
  • bounds checking
  • Reading
    sections 7.1–7.3 of the Introduction to Programming with Java. Important concepts array bounds checking Instructor note In the grand tradition of computer science, the terminology here is confusing. The terms “array,” “list,” “vector,” and “tuple” can all means “an ordered sequence of items indexed by number.” These terms appear across many languages, but their semantics varies a great deal from language to language. For example, for something called an “array”, one language may or may not allow changing the size; it may or may not allow you to change the values stored. But another language may work differently for “array”.
  • pixel
  • Activity
    Keep this syntax handy for reference during the activity. In this activity, you will work with array that contain pixels. A pixel is tiny dot (usually square-shaped) that has a single color. Computer images are made of many pixels arranged in a grid. “Pixel” is short for “picture element.” The plan We are going to write code that takes an input image, reshapes and distorts it, and then displays the resulting image. How will we do the reshaping? By looping over all the pixel coordinates of the output image, and asking for each one: “What input image coordinates should this pixel come from?”
  • raster
  • Activity
    To do a transformation, you’ll need to understand how we put the pixels of a 2-dimensional image into a 1-dimensional array. The array will contain the first row of pixels from left to right, then the second row from left to right, then the third, and so forth. This is called raster order. (Images made of pixels are sometimes called raster images.) For example, if we have a 7×7 pixel image, then the indices of the pixels would be: …so that when we put the pixels in an array, they are arranged like this: (Note that the plural of index is indices.) A tricky part of writing our transformation will be converting back and forth between (x,y) coordinates and array indices. To get started, let’s just copy the image just as before, except using (x,y) coordinates instead of array indices.
  • key-value pair
  • (also called a dictionary or associative array in other languages) keys vs values, key-value pair Things to consider (exercises for yourself, not to turn in) The Java Map interface has the get() method for looking up the value that corresponds to a given key. Why isn’t there a method that goes in the other direction, i.e. looking up the key that corresponds to a given value? Is there a situation where containsKey(x) could return true, but then get(x) returns null? (Yes! What is it?) Your response What do you hope to learn about maps from the in-class activity?
  • Map
  • You know how to go through keys and values of a map using the for-each loop. Introduction A Map is, in addition to List and Set, one of the most widely used of Java’s pre-built data structures. A map is used whenever data is stored as key-value pairs, where values can be added, retrieved, and deleted using keys. Other languages call this data structure a “dictionary,” “associative array,” or “hash table.” The core concept is that a Map contains two kinds of things: keys and values. The connection between those is described using various terms:
  • keys
  • is, in addition to List and Set, one of the most widely used of Java’s pre-built data structures. A map is used whenever data is stored as key-value pairs, where values can be added, retrieved, and deleted using keys. Other languages call this data structure a “dictionary,” “associative array,” or “hash table.” The core concept is that a Map contains two kinds of things: keys and values. The connection between those is described using various terms: The map associates each key with at most one value (hence “associative array”); It maps each key to at most one value (hence “map”); Each key refers to at most one value. For the “dictionary” metaphor: the words are the keys, and the corresponding definition of each word is the value. (If you know Python: Java’s Maps correspond to Python dictionaries
  • values
  • is, in addition to List and Set, one of the most widely used of Java’s pre-built data structures. A map is used whenever data is stored as key-value pairs, where values can be added, retrieved, and deleted using keys. Other languages call this data structure a “dictionary,” “associative array,” or “hash table.” The core concept is that a Map contains two kinds of things: keys and values. The connection between those is described using various terms: The map associates each key with at most one value (hence “associative array”); It maps each key to at most one value (hence “map”); Each key refers to at most one value. For the “dictionary” metaphor: the words are the keys, and the corresponding definition of each word is the value. (If you know Python: Java’s Maps correspond to Python dictionaries.) Just as
  • hash value
  • The hash map is implemented internally in such a way that searching by a key is very fast. The hash map generates a hash value from the key, i.e. a piece of code which is used to store the value of a specific location. When a key is used to retrieve information from a hash map, this particular code identifies the location of the value associated with the key. In practice, it’s not necessary to go through all the key-value pairs in the hash map when searching for a key; the set that’s checked is significantly smaller. We’ll be taking a deeper look into the implementation of a hash map in COMP 128, and compare it to other implementations of the
  • DRY (Don’t Repeat Yourself)
  • Pride and Prejudice (1813) Content: ... null In the above example, we adhered to the DRY (Don’t Repeat Yourself) principle: avoid code duplication. Sanitizing a string, i.e., changing it to lowercase, and trimming, i.e., removing empty characters from the beginning and end, would have been repeated many times in our library class without the sanitizedString method. Repetitive code is often not noticed until it has already been written, which means that it almost always makes its way into the code. There’s nothing wrong with that - the important thing is that the code is cleaned up so that places that require tidying up are noticed.
  • auto-boxing
  • Java converts primitive types to reference types automatically as they are added to either a HashMap or an ArrayList. This automatic conversion to a reference-type value is called auto-boxing in Java, i.e. putting something in a box automatically. The automatic conversion is also possible in the other direction. int key = 2; Map<Integer, Integer> hashmap = new HashMap<>(); hashmap.put(key, 10); int value = hashmap.get(key); System.out.println(value); Output: 10 The following examples describes a class used for counting the number of vehicle license plate sightings. Autoboxing and unboxing takes place in the
  • key (in a Map)
  • Practice the general skill of learning and working with a library’s API Maps Maps pair keys with values. Keys are unique: if a key is present, it has exactly one value. Values are not necessarily unique: multiple keys could have the same value. In this activity, you will learn how to perform common operations with the Map API. Map is an interface (like List), and the most common implementation of Map is HashMap. Thus, if you are creating a map from Student ids (Integers) to Student objects, you would declare and initialize the map using the following:
  • value (in a Map)
  • Practice the general skill of learning and working with a library’s API Maps Maps pair keys with values. Keys are unique: if a key is present, it has exactly one value. Values are not necessarily unique: multiple keys could have the same value. In this activity, you will learn how to perform common operations with the Map API. Map is an interface (like List), and the most common implementation of Map is HashMap. Thus, if you are creating a map from Student ids (Integers) to Student objects, you would declare and initialize the map using the following:
  • breaking change
  • Reading
    , or deleted the class altogether, then your existing code would break. Each of these is an example of what we call a breaking change. There are some changes that are internal to GraphicsGroup, and other changes that are externally visible because they could affect other code that uses GraphicsGroup. This distinction matters. In this class, we are concerned with creating abstractions so that different components of software can change somewhat independently. However, abstractions are only useful if we have an idea of which changes are breaking changes. It is the responsibility of the
  • work if the client & provider of the API agree on their assumptions about the API. We call these shared assumptions the contract of the API. It is possible for an API to make breaking changes, i.e. changes that alter the contract so existing clients won’t work anymore. (Have you ever upgraded your OS or your browser, only to find that some app or web site no longer works? This is why.) Identifying the contract is about identifying which changes could be breaking changes. You can think of a contract as an agreement between the provider and the client of an API: “If the client promises A, B, and C, then the provider promises X, Y, and Z.” This agreement on assumptions both allows and constrains what decoupling may occur.
  • provider
  • Reading
    . This distinction matters. In this class, we are concerned with creating abstractions so that different components of software can change somewhat independently. However, abstractions are only useful if we have an idea of which changes are breaking changes. It is the responsibility of the provider (or “vendor”) of a library like Kilt Graphics to think about what kinds of changes they are making, and whether those changes are externally visible or purely internal. It is the responsibility of clients of Kilt Graphics to learn what it provides, what promises it makes, and what assumptions are safe for client code to make. All this in turn requires some mutual agreement between the provider and the clients of Kilt Graphics about what everyone should expect.
  • client
  • Reading
    (or “vendor”) of a library like Kilt Graphics to think about what kinds of changes they are making, and whether those changes are externally visible or purely internal. It is the responsibility of clients of Kilt Graphics to learn what it provides, what promises it makes, and what assumptions are safe for client code to make. All this in turn requires some mutual agreement between the provider and the clients of Kilt Graphics about what everyone should expect. That agreement is called an API. (It stands for “application programming interface,” but hardly anybody spells that out, even in formal writing. It’s just “API.”) This is an extremely broad term. Here is a definition:
  • remote API
  • Reading
    There are many different kinds of API. Some APIs are for communication between separate computers: A remote API is a protocol for pieces of software to communicate over a network or other physical separation. Remote APIs almost always boil down to rules about reducing all interaction to a sequence of bytes. A web API is a particular kind of remote API that uses the technology of the World Wide Web (things like HTTP, TCP/IP, and DNS). When businesspeople who are not programmers talk about “APIs,” this is usually the specific thing they mean. However, in technical circles, the term “API” is much broader.
  • web API
  • Reading
    is a protocol for pieces of software to communicate over a network or other physical separation. Remote APIs almost always boil down to rules about reducing all interaction to a sequence of bytes. A web API is a particular kind of remote API that uses the technology of the World Wide Web (things like HTTP, TCP/IP, and DNS). When businesspeople who are not programmers talk about “APIs,” this is usually the specific thing they mean. However, in technical circles, the term “API” is much broader. (We don’t deal with remote APIs in this class. The Weather Display exercise does use one! However, the assignment provides the code for interacting with that API, so you don’t need to learn how it works. You may learn about web APIs in COMP 225 and COMP 446, and some of the data science courses as well.)
  • inter-process API
  • Reading
    Some APIs are for communication between different pieces of code running on the same computer: An inter-process API allows separate programs on the same computer to share data. The file system is the most familiar example of this: many programs can read and write the same file, because the computer’s operating system provides a common API for all of them to interact with those files. There are other inter-process communication mechanisms too, such as pipes and sockets. You might get a taste of this in COMP 240. A library is independent code meant for other software projects to use directly, not communicating with another computer or another program, but within the same program. For example, Kilt Graphics is a library. The Java Collections Framework that provides
  • object API
  • Reading
    Unlike remote and inter-process APIs, which tend to be language-independent, this kind of API is language-specific: it exposes its capabilities to clients using the features of one particular programming language. For example, a Java library provides… an object API that specifies a set of public classes and their public and protected methods. This includes not only the signatures (names, parameter types, and return types) of the methods, but also expectations: what a client needs to do to use the classes and their methods, and what the library classes promise (and don’t promise) to do. In fact, a piece of code doesn’t even need to be a library to provide an API. In a large project, we might even choose to imagine that one part of our own program provides an API to other parts, acting as our own unofficial library provider. This relationship can even exist between individual objects.
  • tightly coupled
  • Reading
    APIs help pieces of code change and evolve independently — and thus helps humans work independently but effectively. We say that two components of a system are tightly coupled when changes to one are likely to require changes to the other, and are loosely coupled or (better yet) decoupled when it is easy to change one independently of the other. (These terms come from physical engineering disciplines: Two parts of a physical object can be coupled — joined, attached — tightly together with, for example, welding or glue, so that it is hard to replace or modify one without replacing the other. Conversely, parts can be “loosely coupled” or “decoupled” so that one can be replaced without necessarily replacing the other, e.g. two gears that mesh but are not attached.)
  • loosely coupled
  • Reading
    We say that two components of a system are tightly coupled when changes to one are likely to require changes to the other, and are loosely coupled or (better yet) decoupled when it is easy to change one independently of the other. (These terms come from physical engineering disciplines: Two parts of a physical object can be coupled — joined, attached — tightly together with, for example, welding or glue, so that it is hard to replace or modify one without replacing the other. Conversely, parts can be “loosely coupled” or “decoupled” so that one can be replaced without necessarily replacing the other, e.g. two gears that mesh but are not attached.)
  • decoupled
  • Reading
    when changes to one are likely to require changes to the other, and are loosely coupled or (better yet) decoupled when it is easy to change one independently of the other. (These terms come from physical engineering disciplines: Two parts of a physical object can be coupled — joined, attached — tightly together with, for example, welding or glue, so that it is hard to replace or modify one without replacing the other. Conversely, parts can be “loosely coupled” or “decoupled” so that one can be replaced without necessarily replacing the other, e.g. two gears that mesh but are not attached.)
  • contract
  • work if the client & provider of the API agree on their assumptions about the API. We call these shared assumptions the contract of the API. It is possible for an API to make breaking changes, i.e. changes that alter the contract so existing clients won’t work anymore. (Have you ever upgraded your OS or your browser, only to find that some app or web site no longer works? This is why.) Identifying the contract is about identifying which changes could be breaking changes. You can think of a contract as an agreement between the provider and the client of an API: “If the client promises A, B, and C, then the provider promises X, Y, and Z.” This agreement on assumptions both allows and constrains what decoupling may occur.
  • signature
  • These things are all (1) part of the declaration of classes and methods and (2) can cause a breaking change. We call them the signature of the class or method. (There are a few others we don’t discuss in COMP 127 that are also part of the class signature, such as checked exceptions and the final modifier. You can learn about these things if you ever need them, but for now, don’t worry about these details. The important thing here is the big idea of the “signature.”) For example, consider this class: public class Nessie { private String name; public Nessie(String
  • precondition
  • . It doesn’t matter how a method looks; it matters what it does. People often categorize behavioral contracts into three types: A precondition is something that the API client must guarantee is true before it can call a method (or otherwise perform some action). For example, List’s get(i) has the precondition that 0 i < size(). In GraphicsGroup, the remove(gobj) method has the precondition that the group must contain gobj. A postcondition is something that the API provider guarantees will be true after a method (or other action) completes. For example, List promises that size() will return the number of elements in the list. It also promises that it will not modify the list.
  • postcondition
  • GraphicsGroup, the remove(gobj) method has the precondition that the group must contain gobj. A postcondition is something that the API provider guarantees will be true after a method (or other action) completes. For example, List promises that size() will return the number of elements in the list. It also promises that it will not modify the list. GraphicsGroup promises that after a call to remove(gobj), the group will no longer contain gobj. An invariant is something that an API provider guarantees that any client will always observe to be true about an object, before and after every action. For example, a
  • invariant
  • GraphicsGroup promises that after a call to remove(gobj), the group will no longer contain gobj. An invariant is something that an API provider guarantees that any client will always observe to be true about an object, before and after every action. For example, a List’s size is always nonnegative. A GraphicsObject never belongs to two different CanvasWindows. A subtle point: It is worth noting that an invariant can temporarily break while a method of the object is in the middle of doing its work. However, the invariant must be true again by the time the method is done. The important thing here is that no client of the API can ever
  • . This reading mentions some concepts we have not covered in class, but you should be able to understand the core points. Important concepts defensive programming invariant malicious client internal state defensive copy Things to consider (exercises for yourself, not to turn in) Think of an example of each of the following: class invariant immutable class non-final class window of vulnerability How do you determine whether an object is immutable? Is an immutable object always “safe?” What if you are writing code that is never called by or used by someone who is not on your team? Would you ever still want to practice “defensive programming” to defend against
  • compile-time type
  • of the object it returns? “Runtime type?!?” Here is an explanation of what that question means: The method declaration says it returns a List. That means List is the compile-time type: the method promises to return something that is a List, and List is the type that Java uses to check the code at compile time (i.e. before the code runs). However, List is an interface, and many different classes implement that interface. When the code actually runs, that code will return some specific object, and that object’s class will be some specific class that implements List. That specific class is the runtime type. What class is it? Discuss with your partner.
  • runtime type
  • , that code will return some specific object, and that object’s class will be some specific class that implements List. That specific class is the runtime type. What class is it? Discuss with your partner. When you think you have the answer, check it here: ArrayList Because of that runtime type, the list getCourses() returns is a mutable list. That means we can do this: // Suppose: // - comp127 is a Course // - sally is a Student // - comp127 has no students enrolled yet List<Course> sallyCourses = sally.getCourses(); sallyCourses.add(comp127); System.out.println
  • defensive programming
  • . This reading mentions some concepts we have not covered in class, but you should be able to understand the core points. Important concepts defensive programming invariant malicious client internal state defensive copy Things to consider (exercises for yourself, not to turn in) Think of an example of each of the following: class invariant immutable class non-final class window of vulnerability How do you determine whether an object is immutable? Is an immutable object always “safe?” What if you are writing code that is never called by or used by someone who is not on your team? Would you ever still want to practice “defensive programming” to defend against
  • malicious client
  • . This reading mentions some concepts we have not covered in class, but you should be able to understand the core points. Important concepts defensive programming invariant malicious client internal state defensive copy Things to consider (exercises for yourself, not to turn in) Think of an example of each of the following: class invariant immutable class non-final class window of vulnerability How do you determine whether an object is immutable? Is an immutable object always “safe?” What if you are writing code that is never called by or used by someone who is not on your team? Would you ever still want to practice “defensive programming” to defend against
  • defensive copy
  • Important concepts defensive programming invariant malicious client internal state defensive copy Things to consider (exercises for yourself, not to turn in) Think of an example of each of the following: class invariant immutable class non-final class window of vulnerability How do you determine whether an object is immutable? Is an immutable object always “safe?” What if you are writing code that is never called by or used by someone who is not on your team? Would you ever still want to practice “defensive programming” to defend against
  • model / view separation
  • , and others are only concerned with how the data is presented. This particular separation of concerns is called a model / view separation, and presenting the same data in multiple ways is one of its typical purposes. The same approach to model / view separation that lets you show the song song as both graphics and sound might also, for example, let an email app show the same message data in both a concise form in the inbox, and a detailed form for viewing individual messages. Let’s do it. Create a new SongVisualization class in the audiosynth
  • commit
  • . When you have made some progress… Save your progress with a commit In Git, a commit is a snapshot of your code at a point in time. You can use it to preserve your work as it is now for future reference, in case you want to see what changed or go back to the way it was. Follow these steps every time you have progress worth saving: Open your homework project in GitHub Desktop. In the Changes tab, you will see all the source files you changed. Click on each file, and make sure that all the changes you see are changes that make sense and look good to you. This self-review process is important. Measure twice, cut once!
  • push
  • . Are there things you need to clean up? Just because the code runs doesn’t mean it’s clean or healthy. Submit the assignment by pushing In Git, push means “move commits from one computer to another,” most commonly “move commits from my computer to the cloud.” It is a way of sharing your work with other people — in this case, your instructor and preceptors. You can also use pushing to share work with teammates when you are on a team. (This is how professional developers use it.) Pushing is also a great way of backing up your work in case of laptop disaster! In GitHub Desktop, look in the