Discussion 6

Packages and Bits

Announcements

  1. Project 1 Checkpoint due Friday, 2/25
  2. Lab 6 (part of Enigma) due Friday, 2/25
  3. HW 4 due Tuesday, 3/1

Access Modifiers (in classes)

Can access from... default private protected public
Same class Yes Yes Yes Yes
Subclass in same package Yes No Yes Yes
Non-subclass in same package Yes No Yes Yes
Subclass in different package No No Yes Yes
Non-subclass in same package No No No Yes

"default" is also called package-private.

Bits (Lecture preview)

How do computers represent numbers? In binary (base 2, using 0's and 1's).

The prefix 0b indicates that the number is binary:
0b101 = 4 + 0 + 1

Why should I care, when I can just use base 10?

  • Java numbers use a finite amount of bits
  • Cool math tricks
  • This is what's "under the hood" - 61C!

Additional (surplus) reading: Sections 4.1-4.6 of Dive into Systems

Worksheet

1. Reduce

See worksheet for skeleton

reduce(f, [1, 2, 3, 4, 5]) f(1, 2) f(f(1, 2), 3) f(f(f(1, 2), 3), 4) f(f(f(f(1, 2), 3), 4), 5)

2. Inheritance Infiltration

            
              public class PasswordChecker {
                /** Returns true if the provided login and password are correct. */
                public boolean authenticate(String login, String password) {
                  // Does some secret authentication stuff...
                }
              }
              public class User {
                private String username;
                private String password;
                public void login(PasswordChecker p) {
                  p.authenticate(username, password);
                }
              }
            
          
            
              public class PasswordExtractor extends _______________PasswordChecker {
                String extractedPassword;
                public String extractPassword(User u) {



                }





              }
            
          

3A. A Bit on Bits

            
              /** Returns whether the ith bit of num is a 1 or not. */
              public static boolean isBitIOn(int num, int i) {
                int mask = 1 __________________________________________;
                return ________________________________________________;
              }
            
          

Relevant bit operations:

  • x & y
  • x << n

3B. A Bit on Bits

            
              /** Returns the input number but with its ith bit changed to a 1. */
              public static int turnBitIOn(int num, int i) {
                int mask = 1 __________________________________________;
                return ________________________________________________;
              }
            
          

Relevant bit operations:

  • x | y
  • x << n (again!)