Home Collegeboard - Classes
Post
Cancel

Collegeboard - Classes

U5 | Classes


5.1 Anatomy of a Class & 5.2 Constructors

Methods vs Constructors

  • Methods: functions defined within a class that preforms specific actions for objects of that class

  • Constructors: special methods in a class that are responsible for initializing the object’s state when an instance of the class is created

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// EXAMPLE CLASS
public class Snack {
    // Instance Variables
    private String name;
    private int calories;

    // Default Constructor
    public Snack() {
        name = "";
        calories = 0;
    }

    // Overloaded Constructor
    public Snack (string n, int c) {
        name = n;
        calories = c;
    }

    // Accessor method 1
    public String getName() {
        return name;
    }

    // Access method 2
    public int getCalories() {
        return calories;
    }

    // Mutator method 1
    public void setName(String n) {
        name = n;
    }

    // Mutator method 2
    public void setCalories(int c) {
        calories = c;
    }

    private boolean canEat() {
        return (calories < 150);
    }
}

private vs public

  • public: allows access from classes outside the declaring class (classes, constructors)

  • private: restricts access to the declaring class (instance variables)

methods can be either public or private

Popcorn Hack: Which of the following lines will cause an error?

1
2
3
4
5
6
7
8
9
10
public class SnackDriver {
    public static void main(String[] args) {
        Snack choiceOne = new Snack("cookies", 100);
        Snack choiceTwo = new Snack();
        System.out.println(choiceOne.getName());
        System.out.println(choiceOne.getCalories());
        choiceTwo.setName("chips");
        choiceTwo.calories = 150; // error because calories is private
    }
}

Key term: Encapsulation

  • A fundmanetal concept of OOP
  • Wraps the data (variable) and code that acts on the data (methods) in one unit (class)
  • In AP CSA we do this by:
    • Writing a class
    • Declaring the instance variables as private –> enforce constraints and ensure integrity of data
    • Providing accessor (get) methods and modifier (set) methods to view and modify variables outside of the class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Sport {
    private String name;
    private int numAthletes;

    public Sport () {
        name = "";
        numAthletes = 0;
    }

    // Parameters in contructors are local variables
    public Sport (String n, int numAth) {
        name = n;
        numAthletes = numAth;
    }

    // What if not all instance variables are set through parameters?
    public Sport (String n) {
        name = n;
        numAthletes = 0;
    }
}

Sport tbd = new Sport();
Sport wp = new Sport("Water Polo", 14);
Sport wp = new Sport("Volleyball");
  • if no constructor provided, Java provides default constructor: int (0), double (0.0), strings and other objects (null)

Hacks

Create a Book class where each book has a title, genre, author, and number of pages. Include a default and overloaded constructor.

Without Override

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
public class Book {
    private String title;
    private String genre;
    private String author;
    private int pages;

    public Book() {
        title = "n/a";
        genre = "n/a";
        author = "n/a";
        pages = 0;
    }

    public Book(String title, String genre, String author, int pages) {
        this.title = title;
        this.genre = genre;
        this.author = author;
        this.pages = pages;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getGenre() {
        return genre;
    }

    public void setGenre(String genre) {
        this.genre = genre;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public int getPages() {
        return pages;
    }

    public void setPages(int pages) {
        this.pages = pages;
    }

    // @Override
    // public String toString() {
    //     return title + genre + author + pages;
    // }

    public static void main(String[] args) {
        Book book = new Book("Book", "Fiction", "John Doe", 876);
        System.out.println(book);
    }
}

Book.main(null);

1
REPL.$JShell$13K$Book@23e7367b

With Override

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
public class Book {
  private String title;
  private String genre;
  private String author;
  private int pages;

  public Book() {
      title = "n/a";
      genre = "n/a";
      author = "n/a";
      pages = 0;
  }

  public Book(String title, String genre, String author, int pages) {
      this.title = title;
      this.genre = genre;
      this.author = author;
      this.pages = pages;
  }

  public String getTitle() {
      return title;
  }

  public void setTitle(String title) {
      this.title = title;
  }

  public String getGenre() {
      return genre;
  }

  public void setGenre(String genre) {
      this.genre = genre;
  }

  public String getAuthor() {
      return author;
  }

  public void setAuthor(String author) {
      this.author = author;
  }

  public int getPages() {
      return pages;
  }

  public void setPages(int pages) {
      this.pages = pages;
  }

  @Override
  public String toString() {
      return "Title: " + title + ", Genre: " + genre + ", Author: " + author + ", Pages: " + pages;
  }

  public static void main(String[] args) {
      Book book = new Book("Book", "Fiction", "John Doe", 876);
      System.out.println(book);
  }
}

Book.main(null);
1
Title: Book, Genre: Fiction, Author: John Doe, Pages: 876

5.3 Documentation with Comments

REMEMBER: comments are ignored by the compiler and anything written in them won’t execute

  • they’re used for people to make code more readable.. allows them to understand what’s happening without having to go further into the code
  • improves communication between TEAMS
  • allows code to be maintained over years
  • prevents execution when testing alternative code

You are NOT required to write comments of AP Exam FRQs, but it is always a good habit

The types of comments:

1) Single line: // 2) Multiline: /* */ 3) Java Doc: /** * * */

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* 
    Programmer: 
    Date: 
    Purpose 
 */

 public class Main {
    public static void main(String[] args) {
        // variables
        double length = 2.5;
        double width = 4;

        //.. and so on
    }
}


/** 
 * javadoc comments:
 * jkafhjdajhf
 * 
 * @author
 * @version 
 */

Javadoc is a tool that pulls any comments written in this format to make a documentation of the class in the form of a webpage

Javadoc also has tags (as shown above)

Preconditions: conditions that must be met before the execution of a code in order for it to run correctly

  • Will be written in comments for a method for most APCSA questions
  • it is assumed that these preconditions are true, we do not need to check!

Postconditions: conditions that must be met after the conditions has been executed (outcome, state of variables, ect)

  • Will be written in comments for a method for most APCSA questions
  • we do have to check to make sure these have been met
  • good way to get a summary of what you need to be doing
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// EXAMPLE FROM AP CLASSROOM:

public class SecretWord {
    private String word;

    public SecretWord(String w) {
        word = w;
    }

    /** 
     * Precondition: parameter num is less than the length of word
     * Postcondition: Returns the string of the characters of word from the index hum to the end of the word followed by the characters of word from index 0 to num, not including index num. The state of word has not changed
     */

    public String newWord(int num)
    {
        //implementation not shown
    }
}

5.4 Accessor Method

OUR GOAL: to define behaviors of an object through non-void methods NOT using parameters written in a class

REMEMBER: an accessor method allows other objects to access static variables

What is the purpose of an accessor method?

It allows us to safely access variables without other people being able to. Also called get methods or getters.

They’re necessary whenever another class needs to access a variable outside of that class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Example class 

public class Movie {
    // private instance variables
    private String name;
    private int runtime;

    // default constructor 
    public Movie() {
        name = "";
        runtime = 0;
    }

    // overloaded constructor:
    public Movie(String n, int c) {
        name = n;
        runtime = c;
    }

    // added ACCESSOR METHOD for each variable

    public String getName() { // header 
        return name; // returning a COPY of the private instance variables
    }

    public int getRuntime() {
        return runtime;
    }
}

An accessor method must be:

  • public in order to be accessible
  • the return type must match the instance variable type
  • usually name of method is getNameOfVariable
  • should be NO PARAMETERS

POPCORN HACKS: write an accessor method for each of the instance variables:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Course {
    private String name;
    private String gradeLevel;
    private int period;

    public String getName() {
        return name;
    }

    public String getGradeLevel() {
        return gradeLevel;
    }

    public int getPeriod() {
        return period;
    }
}

Let’s look at another example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Sport {

    private String name;
    private int numAthletes;

    public Sport(String n, int num) {
        name = n;
        numAthletes = sum;
    }

    public String getName() {
        return name;
    }

    public int getNumAthletes () {
        return numAthletes;
    }
}

Can we print out information about an instance of this object?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class Sport {
    private String name;
    private int numAthletes;

    public Sport(String n, int num) {
        name = n;
        numAthletes = num;
    }

    public String getName() {
        return name;
    }

    public int getNumAthletes() {
        return numAthletes;
    }

    public static void main(String[] args) {

        Sport volleyball = new Sport("volleyball", 12);

        System.out.println(volleyball);
    }
}

Sport.main(null);
1
REPL.$JShell$15$Sport@31be33a0

What output did we get?

the code outputs the object class in the form of classname@hashcode in hexadecimal


let’s try using the tostring method:

  • returns a string when System.out.println(object) is called
  • no parameters
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Sport {
    private String name;
    private int numAthletes;

    public Sport(String n, int num) {
        name = n;
        numAthletes = num;
    }

    public String getName() {
        return name;
    }

    public int getNumAthletes() {
        return numAthletes;
    }

    public String toString() { // toString method.. HEADER MUST BE WRITTEN IN THIS WAY
        return "Sport: " + name +"\nNumber of Athletes: " + numAthletes;
    }

    public static void main(String[] args) {

        Sport volleyball = new Sport("volleyball", 12);

        System.out.println(volleyball);
    }
}

Sport.main(null);
1
2
Sport: volleyball
Number of Athletes: 12

5.5. Mutators / Setters

Purpose: Mutators are used to change the values of the fields (attributes) of an object.

Access Control: Mutators are typically defined as public methods to allow external code to modify the object’s state.

Naming Convention: The method names for mutators usually start with “set” followed by the name of the field they modify.

Parameterized: Mutators take one or more parameters that represent the new values for the fields.

Return Type: Mutators are usually of type void, as they don’t return a value, but they modify the object’s state.

Encapsulation: Mutators are an essential part of encapsulation, which helps to protect the object’s state by controlling access through methods.

Validation: Mutators often include validation logic to ensure that the new values being set are within acceptable bounds or meet specific criteria.

Example Usage: Mutator for setting the age of a Person object might look like: public void setAge(int newAge) {…}.

Chaining: Mutators can be chained together in a single line for more fluent and concise code, e.g., person.setName(“John”).setAge(30);.

Immutable Objects: In some cases, mutators are not used, and instead, a new object with modified values is created. This approach is common in creating immutable objects in Java.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
public class UserAccount {
    private String username;
    private String password;
    private boolean isLoggedIn;

    public UserAccount(String username, String password) {
        this.username = username;
        this.password = password;
        this.isLoggedIn = false;
    }

    // Mutator for setting the username
    public void setUsername(String newUsername) {
        this.username = newUsername;
    }

    // Mutator for setting the password
    public void setPassword(String newPassword) {
        this.password = newPassword;
    }

    // Mutator for logging in
    public void login(String enteredUsername, String enteredPassword) {
        if (enteredUsername.equals(username) && enteredPassword.equals(password)) {
            isLoggedIn = true;
            System.out.println("Login successful. Welcome, " + username + "!");
        } else {
            System.out.println("Login failed. Please check your username and password.");
        }
    }

    // Mutator for logging out
    public void logout() {
        isLoggedIn = false;
        System.out.println("Logged out successfully.");
    }

    // Accessor for checking if the user is logged in
    public boolean isLoggedIn() {
        return isLoggedIn;
    }

    public static void main(String[] args) {
        // Create a UserAccount
        UserAccount userAccount = new UserAccount("alice", "password123");

        // Attempt to log in
        userAccount.login("alice", "password123");

        // Check if the user is logged in
        if (userAccount.isLoggedIn()) {
            // Access the Scrum board or other features here
            System.out.println("Accessing Scrum boards...");
        } else {
            System.out.println("Access denied. Please log in.");
        }

        // Log out
        userAccount.logout();
    }
}

Hacks

Create a Java class BankAccount to represent a simple bank account. This class should have the following attributes:

  • accountHolder (String): The name of the account holder. balance (double): The current balance in the account. Implement the following mutator (setter) methods for the BankAccount class:

  • setAccountHolder(String name): Sets the name of the account holder.
  • deposit(double amount): Deposits a given amount into the account.
  • withdraw(double amount): Withdraws a given amount from the account, but only if the withdrawal amount is less than or equal to the current balance.

Ensure that the balance is never negative.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class BankAccount {
    private String accountHolder;
    private double balance;

    public BankAccount(String accountHolder, double balance) {
        this.accountHolder = accountHolder;
        this.balance = balance;
    }

    public void setAccountHolder(String name) {
        accountHolder = name;
    }

    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
        }
    }

    public static void main(String[] args) {
        BankAccount account = new BankAccount("John Doe", 1000.0);

        account.setAccountHolder("Jane Doe");
        account.deposit(500.0);
        account.withdraw(200.0);

        System.out.println("Account holder: " + account.accountHolder);
        System.out.println("Current balance: " + account.balance);
    }
}

BankAccount.main(null);
1
2
Account holder: Jane Doe
Current balance: 1300.0

5.6 Writing Methods

  • Method Declaration: Define methods using the method keyword, specifying return type, method name, and parameters.
  • Method Parameters: Methods can take input parameters.
  • Return Statement: Use the return statement to return a value from a method.
  • Method Overloading: You can have multiple methods with the same name but different parameter lists.
  • Static Methods: Static methods are associated with the class rather than instances.
  • Instance Methods: Instance methods are associated with an object of the class.
  • Access Modifiers: Use access modifiers like public, private, or protected to control visibility.
  • Method Invocation: Call methods using the dot notation on objects or classes (for static methods).
  • Recursive Methods: Methods can call themselves, creating recursive functions.
  • Varargs (Variable-Length Argument Lists): Use varargs to pass a variable number of arguments to a method.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class Calculator {
    public int add(int operand1, int operand2) {
        return operand1 + operand2;
    }

    public int subtract(int operand1, int operand2) {
        return operand1 - operand2;
    }

    public int multiply(int operand1, int operand2) {
        return operand1 * operand2;
    }

    public int divide(int dividend, int divisor) {
        if (divisor != 0) {
            return dividend / divisor;
        } else {
            throw new ArithmeticException("Division by zero is not allowed.");
        }
    }

    public static void main(String[] args) {
        Calculator calculator = new Calculator();
        int resultAdd = calculator.add(5, 3);
        int resultSubtract = calculator.subtract(10, 7);
        int resultMultiply = calculator.multiply(4, 6);
        int resultDivide = calculator.divide(8, 2);

        System.out.println("Addition: " + resultAdd);
        System.out.println("Subtraction: " + resultSubtract);
        System.out.println("Multiplication: " + resultMultiply);
        System.out.println("Division: " + resultDivide);
    }
}

Hacks

Create a Java class MathUtility with a set of utility methods for mathematical operations. Implement the following methods:

  • calculateAverage(double[] numbers): Calculate the average of an array of numbers.
  • isPrime(int number): Check if a given integer is prime.
  • findFactors(int number): Find and return an array of factors for a given integer. Include proper error handling for edge cases and invalid input.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
public class MathUtility {
    public double calculateAverage(double[] numbers) {
        double sum = 0.0;
        for (double number : numbers) {
            sum += number;
        }
        return sum / numbers.length;
    }

    public boolean isPrime(int number) {
        if (number <= 1) {
            return false;
        }
        if (number <= 3) {
            return true;
        }
        if (number % 2 == 0 || number % 3 == 0) {
            return false;
        }

        for (int i = 5; i * i <= number; i += 6) {
            if (number % i == 0 || number % (i + 2) == 0) {
                return false;
            }
        }
        return true;
    }

    public int[] findFactors(int number) {
        int count = 0;
        for (int i = 1; i <= number; i++) {
            if (number % i == 0) {
                count++;
            }
        }

        int[] factors = new int[count];
        int index = 0;
        for (int i = 1; i <= number; i++) {
            if (number % i == 0) {
                factors[index] = i;
                index++;
            }
        }

        return factors;
    }

    public static void main(String[] args) {
        MathUtility mathUtility = new MathUtility();

        double[] numbers = {1, 2, 3, 4, 5, 6};
        double average = mathUtility.calculateAverage(numbers);
        System.out.println("Average of the numbers: " + average);

        int numberToCheck = 17;
        boolean isPrime = mathUtility.isPrime(numberToCheck);
        System.out.println(numberToCheck + " is prime: " + isPrime);

        int numberToFactor = 12;
        int[] factors = mathUtility.findFactors(numberToFactor);
        System.out.print("Factors of " + numberToFactor + ": ");
        for (int factor : factors) {
            System.out.print(factor + " ");
        }
    }
}
MathUtility.main(null);
1
2
3
Average of the numbers: 3.5
17 is prime: true
Factors of 12: 1 2 3 4 6 12 

5.7 Static Variables and Methods

Static Methods

  • Define behaviors of a class (belong to class, NOT object)
  • Keyword static in header before method name
  • Can only: access/change static variables
  • Can’t: access/change instance variables or the class’ instance variables, no this reference

Practice

Should we use a static or non-static method?
1
2
3
4
5
6
7
8
9
public class Assignment{
    // next classwork/homework ID is NEXT number of classwork/homework that will be created
    private static int nextClassworkID = 1;
    private static int nextHomeworkID = 1;
    private String name;
    private int pointValue;

    // constructors and methods not shown
}

Question: What is the static data and what is the instance data?

Answer: nextClassworkID and nextHomeworkID is the static data, name and pointValue is for instances

Question: A method getGrade is given an int score earned on the assignment and returns the percentage (as a decimal) earned by that score. Would this be implemented as a static or non-static method?

  • Think: What data does it need access to? If needs access to instance data, needs to be non-static. If only need access to static data, it can be static.

Answer: non-static, since the method would need to access pointValue which is an instance variable.

Popcorn Hacks: write getGrade method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
public class Assignment {
    private static int nextClassworkID = 1;
    private static int nextHomeworkID = 1;
    private String name;
    private int pointValue;
    private int classworkID;
    private int homeworkID;
    private int studentScore = -1;

    public Assignment(String name, int pointValue, boolean isClasswork) {
        this.name = name;
        this.pointValue = pointValue;
        if (isClasswork) {
            this.classworkID = nextClassworkID++;
        } else {
            this.homeworkID = nextHomeworkID++;
        }
    }

    public void setStudentScore(int score) {
        if (score >= 0 && score <= pointValue) {
            studentScore = score;
        } else {
            System.out.println("Invalid score. Score must be between 0 and " + pointValue);
        }
    }

    public int getStudentScore() {
        return studentScore;
    }

    public boolean isClasswork() {
        return classworkID > 0;
    }

    public boolean isHomework() {
        return homeworkID > 0;
    }

    public String getDescription() {
        return name + " (ID: " + (isClasswork() ? "C" + classworkID : "H" + homeworkID) + ")";
    }

    public char getGrade() {
        if (studentScore < 0) {
            return ' ';
        }
        double percentage = (double) studentScore / pointValue * 100;
        if (percentage >= 90) {
            return 'A';
        } else if (percentage >= 80) {
            return 'B';
        } else if (percentage >= 70) {
            return 'C';
        } else if (percentage >= 60) {
            return 'D';
        } else {
            return 'F';
        }
    }

    @Override
    public String toString() {
        return "Assignment: " + name + "\n" +
               "Type: " + (isClasswork() ? "Classwork" : "Homework") + "\n" +
               "Point Value: " + pointValue + "\n" +
               "Student Score: " + (studentScore < 0 ? "Not graded" : studentScore) + "\n" +
               "Grade: " + getGrade();
    }

    public static void main(String[] args) {
        Assignment classwork1 = new Assignment("Classwork 1", 20, true);
        Assignment homework1 = new Assignment("Homework 1", 50, false);

        System.out.println(classwork1.getDescription());
        classwork1.setStudentScore(18);
        System.out.println(classwork1);

        System.out.println(homework1.getDescription());
        homework1.setStudentScore(45);
        System.out.println(homework1);
    }
}
Assignment.main(null);
1
2
3
4
5
6
7
8
9
10
11
12
Classwork 1 (ID: C1)
Assignment: Classwork 1
Type: Classwork
Point Value: 20
Student Score: 18
Grade: A
Homework 1 (ID: H1)
Assignment: Homework 1
Type: Homework
Point Value: 50
Student Score: 45
Grade: A

Question: Would a method that reports the total number of assignments be static or non-static?

Answer: static, since the method would only need to access static data

Popcorn Hacks: write this method totalAssign

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class Assignment {
    private static int nextClassworkID = 0;
    private static int nextHomeworkID = 0;
    private String name;
    private int pointValue;

    public Assignment(String name, int pointValue) {
        this.name = name;
        this.pointValue = pointValue;
        if (this instanceof Classwork) {
            nextClassworkID++;
        } else if (this instanceof Homework) {
            nextHomeworkID++;
        }
    }

    public static int totalAssign() {
        return nextClassworkID + nextHomeworkID;
    }

    public static void main(String[] args) {
        Assignment classwork1 = new Classwork("Classwork 1", 10);
        Assignment classwork2 = new Classwork("Classwork 2", 15);
        Assignment homework1 = new Homework("Homework 1", 20);
        Assignment homework2 = new Homework("Homework 2", 25);

        System.out.println("Total number of assignments: " + Assignment.totalAssign());
    }
}

class Classwork extends Assignment {
    public Classwork(String name, int pointValue) {
        super(name, pointValue);
    }
}

class Homework extends Assignment {
    public Homework(String name, int pointValue) {
        super(name, pointValue);
    }
}

Assignment.main(null);
1
Total number of assignments: 4

Multiple Choice Question

1
2
3
4
5
6
7
8
9
10
11
12
public class Example{
    private static int goal = 125;
    private int current;

    public Example (int c) {
        // code segment 1
    }
    public static void resetGoal (int g) {
        // code segment 2
    }
    // other methods not shown
}

Which of the following statements is true?

  1. Code segment 1 can use the variable goal but cannot use the variable current.
  2. Code segment 1 cannot use the variable goal but can use the variable current.
  3. Code segment 2 can use the variable goal but cannot use the variable current. <–
  4. Code segment 2 cannot use the variable goal but can use the variable current.
  5. Both code segments have access to both variables

Question: Which ones can code segment 1 (constructor) use?

Code segment 1 can use goal and current.

Static Variables

  • Define static variables that belong to the class, all object of the class sharing that single static variable (associated with class, NOT objects of class)
  • Either public or private
  • static keyword before variable type
  • used with class name and dot operator

Multiple Choice Question

1
2
3
4
5
6
7
8
9
10
11
12
public class Example{
    private static int goal = 125;
    private int current;

    public Example (int c) {
        // code segment 1
    }
    public static void resetGoal (int g) {
        // code segment 2
    }
    // other methods not shown
}

Which of the following statements is true?

  1. Objects e1 and e2 each have a variable goal and variable current.
  2. Objects e1 and e2 share the variable goal and share the variable current.
  3. Objects e1 and e2 share the variable goal and each have a variable current. <–
  4. Objects e1 and e2 each have a variable goal and share the variable goal and share the variable current.
  5. The code does not complie because static variables must be public.

5.8 Scope and Access

  • Local variables: variables declared in body of constructors and methods, only use within constructor or method, can’t be declared public or private
  • If local variable named same as instance variable, within that method the local variable will be referred to
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Bowler{
    private int totalPins;
    private int games;
    
    public Bowler(int pins){
        totalPins = pins;
        games = 3;
    }

    public void update (int game1, int game2, int game3) {
        // local variable here is newPins
        int newPins = game1 + game2 + game3;
        totalPins += newPins;
        games += 3;
    }
}

Multiple Choice Question

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Example{
    private int current;
    
    public Example(int c){
        double factor = Math.random();
        current = (int)(c * factor);
    }

    public void rest (int num) {
        private double factor = Math.random();
        current += (int)(num * factor)
    }
    
    // other methods not shown
}

Which of the following is the reason this code does not compile?

  1. The reset method cannot declare a variable named factor since a vriable named factor is declared in the constructor.
  2. The reset method cannot declare factor as private since factor is a local variable not an instance variable.
  3. The constructor cannot declare a variable named factor since a variable named factor is declared in the reset method. <–
  4. The constructor cannot access the isntance variable current since current is private.
  5. There is no syntax error in this code and it would compile.

5.9 this Keyword

this keyword

a keyword that essentially refers to the object that is calling the method or the object that the constructor is trying to make

Can be used 3 Ways:

  1. refer to instance variable > This will solve the problem of having duplicate variable names. To distinguish the instance and local variables, we use this.variableName for the instance variable and simply variableName for the local variable.

  2. parameter > Sometimes, we can also use the object as a parameter in its own method call to use itself in the method by using objectName.methodName(this).

  3. constructor or method call > Sometimes, we can also use the object as a parameter in its own method call to use itself in the method by using objectName.methodName(this).

Using this() in a constructor » Calls the no-arg constructor or the constructor without any parameters of the current class, can also call other constructor that hav parameters by passing correct numb and type of args between parenthesis

^^ using this() can help you reuse code from one constructor in another

this in Java » is limited to current object = only be used to access instance variables and invoke non-static methods

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Dog {
    private String breed;

    public String getBreed(){
        return breed;
    }

    public boolean isSameBreed(Dog otherDog){
        return         
        // breed.equals(otherDog.getBreed());
        // this.breed.equals(otherDog.getBread());
        // **this** makes the code more readable/clear but is not required
    }
}
1
2
3
4
5
6
7
8
9
10
public class DogCompetition {

    public boolean doBreedMatch (Dog dog1, Dog dog2){
        return this.getBreed().equals(dog2.getBreed());
        // **this** refers to object which was used to call doBreedsMatch and is a DogCompetition object, not dog object (CANNOT CALL getBreed())
        // this.dog1
        // dog1 is not data member (parameter) so incorrect
        // doBreedMatch doesn't use any data from DogCompetition class no way to use this
    }
}

Local vs Instance

Make the code a little clearer by using the this keyword

b,a,w,and s aren’t meaningful parameters change them into breed, age, weight, and score

distinguish the local and instance variables using the this keyword

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private String breed;
public class Dog {
    private int age;
    private double weight;
    private double score;

    public Dog(sting b, int a, double w, double s){
        // 1. make this code a little clearer by using the **this** keyword
        // 2. change the parameters into something more meaningful
        // 3. distinguish local vs instance variables using **this** keyword
        breed = b;
        age = a;
        weight = w;
        score - s;
    }
}

HACKS

  1. what does using this() in a constructor mean in your own words
  • It is a method that can only be accesses within it’s specific instance. Basically can be used as a temporary variable that is used while the instance of something is running and then will be deleted or used in another instance.

5.10 Ethical and Social Implications of Computing Systems

Impacts

Programming affects the world in many ways, such as socially, economically, and culturally. For instance, not everyone has the same access to technology and computer programs, which creates social inequalities. Some people can use technology, while others can’t. Digital Divide

The global economy relies heavily on technology and computer programs, especially in areas like stock trading and economic predictions. Programming and technology have also made the world more connected, allowing different cultures to mix and making it easier for people to communicate globally. However, this has also created a gap between generations, with younger people having more exposure to digital technology than older generations.

These impacts on society, the economy, and culture can be both good and bad.

System Reliability

When programmers create software, they need to consider how reliable the system is. Different devices can perform the same task at varying speeds and in different ways. Each system may have security issues that hackers can exploit.

To make systems more reliable, programmers need to fix any bugs as soon as they find them. These fixes are then released to users as updates or patches to ensure that computers can be used safely and correctly.

Intellectual Property

Usually, when people create programs on the internet, they own them. However, open source programs blur this line. In open source programs, anyone can make improvements to the code if the program owner allows it.

Licensing and access also play a role in letting others adapt and build on existing code to create their own programs. There are different types of licenses, like Creative Commons and MIT License, each serving different purposes.

Here is an article on how to add a license on your Repository

HACKS

As a team decide what license you want and add it to your repository (add a screenshot of it in your team ticket)

This post is licensed under CC BY 4.0 by the author.

Plan 9

Class Structure