Calling Instance Methods
Popcorn hack #1
public class Dog {
private String name;
private String breed; // Added property for breed
public Dog(String name, String breed) {
this.name = name;
this.breed = breed;
}
public void bark() {
System.out.println(name + " says: Woof!");
}
public void printBreed() {
System.out.println("My dog " + name + " is a " + breed + "!");
}
}
// To use it:
Dog d = new Dog("Aadi", "Bhat"); // create an instance
d.bark(); // call the bark method
d.printBreed(); // call the printBreed method
Aadi says: Woof!
My dog Aadi is a Bhat!
Popcorn #2
public class Counter {
private int count;
public void add(int x) {
count += x;
}
public void subtract(int x) {
count -= x;
}
public void multiply(int x) {
count *= x;
}
public void divide(int x) {
if (x != 0) {
count /= x;
} else {
System.out.println("Division by zero is not allowed.");
}
}
public int getCount() {
return count;
}
}
// Use it:
Counter c = new Counter();
c.add(5); // Add 5
System.out.println(c.getCount()); // Output: 5
c.subtract(2); // Subtract 2
System.out.println(c.getCount()); // Output: 3
c.multiply(4); // Multiply by 4
System.out.println(c.getCount()); // Output: 12
c.divide(3); // Divide by 3
System.out.println(c.getCount()); // Output: 4
c.divide(0); // Attempt division by 0
5
3
12
4
Division by zero is not allowed.
MCQs
// MCQ #1
public class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
balance = initialBalance;
}
public void deposit(double amount) {
balance += amount;
}
public double getBalance() {
return balance;
}
}
BankAccount account = new BankAccount(100.0);
account.deposit(50.0);
double total = account.getBalance(); // answer is B
// MCQ #2
public class Rectangle {
private int length;
private int width;
public Rectangle(int l, int w) {
length = l;
width = w;
}
public int getArea() {
return length * width;
}
public void scale(int factor) {
length *= factor;
width *= factor;
}
}
Rectangle rect = new Rectangle(3, 4);
rect.scale(2);
System.out.println(rect.getArea()); // answer is C
48
MCQ 3 Which of the following best describes when a NullPointerException will occur when calling an instance method?
A. When the method is declared as void
B. When the method is called on a reference variable that has not been initialized to an object
C. When the method’s parameters do not match the arguments provided
D. When the method is called from outside the class
E. When the method attempts to return a value but is declared as void
B. When the method is called on a reference variable that has not been initialized to an object
Explanation:
A NullPointerException occurs when you attempt to call an instance method on a reference variable that is null, meaning it has not been initialized to point to an actual object in memory.
// MCQ #4
public class Temperature {
private double celsius;
public Temperature(double c) {
celsius = c;
}
public double getFahrenheit() {
return celsius * 9.0 / 5.0 + 32;
}
public void setCelsius(double c) {
celsius = c;
}
}
Temperature temp = new Temperature(15);
int result = temp.setCelsius(30); // answer is D
| int result = temp.setCelsius(30);
incompatible types: void cannot be converted to int
// MCQ #5
public class Book {
private String title;
private int pages;
public Book(String t, int p) {
title = t;
pages = p;
}
public String getTitle() {
return title;
}
public int getPages() {
return pages;
}
public void addPages(int additional) {
pages += additional;
}
}
Book novel = new Book("Java Basics", 200);
novel.addPages(50);
System.out.println(novel.getPages()); // answer is D
250
Homeowork Hack
public class Student {
private String name;
private int totalPoints;
private int numberOfAssignments;
// Constructor to initialize the student's name and set initial values
public Student(String name) {
this.name = name;
this.totalPoints = 0;
this.numberOfAssignments = 0;
}
// Void instance method to add a grade
public void addGrade(int grade) {
totalPoints += grade;
numberOfAssignments++;
}
// Non-void instance method to calculate the average grade
public double getAverage() {
if (numberOfAssignments == 0) {
return 0.0;
}
return (double) totalPoints / numberOfAssignments;
}
// Non-void instance method to determine the letter grade
public String getLetterGrade() {
double average = getAverage();
if (average >= 90) {
return "A";
} else if (average >= 80) {
return "B";
} else if (average >= 70) {
return "C";
} else if (average >= 60) {
return "D";
} else {
return "F";
}
}
// Void instance method to print the grade report
public void printReport() {
System.out.println("Grade Report for " + name + ":");
System.out.println("Total Points: " + totalPoints);
System.out.println("Number of Assignments: " + numberOfAssignments);
System.out.printf("Average: %.2f\n", getAverage());
System.out.println("Letter Grade: " + getLetterGrade() + "\n");
}
// Main method to demonstrate the functionality
public static void main(String[] args) {
System.out.println("=== Homework: Assignment Overview ===\n");
// Creating student: Alice
System.out.println("Creating student: Alice");
Student alice = new Student("Alice");
System.out.println("Student created successfully!\n");
// Adding Grades for Alice
System.out.println("--- Adding Grades for Alice ---");
alice.addGrade(95);
alice.addGrade(88);
alice.addGrade(92);
// Alice's Grade Report
alice.printReport();
// Creating student: Bob
System.out.println("Creating student: Bob");
Student bob = new Student("Bob");
System.out.println("Student created successfully!\n");
// Adding Grades for Bob
System.out.println("--- Adding Grades for Bob ---");
bob.addGrade(78);
bob.addGrade(82);
bob.addGrade(75);
// Bob's Grade Report
bob.printReport();
}
}
// Call the main method to print the output
Student.main(null);
=== Homework: Assignment Overview ===
Creating student: Alice
Student created successfully!
--- Adding Grades for Alice ---
Grade Report for Alice:
Total Points: 275
Number of Assignments: 3
Average: 91.67
Letter Grade: A
Creating student: Bob
Student created successfully!
--- Adding Grades for Bob ---
Grade Report for Bob:
Total Points: 235
Number of Assignments: 3
Average: 78.33
Letter Grade: C
Homework Hack
import java.util.ArrayList;
public class Student {
public String name;
private ArrayList<Integer> grades;
public Student(String name) {
this.name = name;
this.grades = new ArrayList<>();
}
public void addGrade(int grade) {
grades.add(grade);
}
public double getAverage() {
if (grades.isEmpty()) {
return 0.0;
}
double sum = 0;
for (int grade : grades) {
sum += grade;
}
return sum / grades.size();
}
public String getLetterGrade() {
double average = getAverage();
if (average >= 90) {
return "A";
} else if (average >= 80) {
return "B";
} else if (average >= 70) {
return "C";
} else if (average >= 60) {
return "D";
} else {
return "F";
}
}
public void printReport() {
System.out.println("Grade Report for " + name + ":");
System.out.println("Grades: " + grades);
System.out.printf("Average: %.2f\n", getAverage());
System.out.println("Letter Grade: " + getLetterGrade() + "\n");
}
}
// Main class
public class Main {
public static void main(String[] args) {
System.out.println("=== Student Grade Tracker System ===\n");
// Creating student: Emma Rodriguez
System.out.println("Creating student: Emma Rodriguez");
Student emma = new Student("Emma Rodriguez");
System.out.println("Student created successfully!\n");
// Adding Grades for Emma
System.out.println("--- Adding Grades for Emma ---");
emma.addGrade(95);
emma.addGrade(88);
emma.addGrade(92);
emma.addGrade(85);
// Emma's Grade Report
emma.printReport();
// Creating student: James Wilson
System.out.println("Creating student: James Wilson");
Student james = new Student("James Wilson");
System.out.println("Student created successfully!\n");
// Adding Grades for James
System.out.println("--- Adding Grades for James ---");
james.addGrade(78);
james.addGrade(82);
james.addGrade(75);
// James's Grade Report
james.printReport();
// Final Summary
System.out.println("Final Summary:");
System.out.printf("%s - Average: %.2f (%s)\n", emma.name, emma.getAverage(), emma.getLetterGrade());
System.out.printf("%s - Average: %.2f (%s)\n", james.name, james.getAverage(), james.getLetterGrade());
}
}
Main.main(null);
=== Student Grade Tracker System ===
Creating student: Emma Rodriguez
Student created successfully!
--- Adding Grades for Emma ---
Grade Report for Emma Rodriguez:
Grades: [95, 88, 92, 85]
Average: 90.00
Letter Grade: A
Creating student: James Wilson
Student created successfully!
--- Adding Grades for James ---
Grade Report for James Wilson:
Grades: [78, 82, 75]
Average: 78.33
Letter Grade: C
Final Summary:
Emma Rodriguez - Average: 90.00 (A)
James Wilson - Average: 78.33 (C)
Comments on Self-Grade
-
Functionality (40%)
The program runs without any errors and successfully creates multipleStudentobjects. Grades are added correctly, averages are calculated accurately, and letter grades are assigned as per the rubric. The functionality is complete and meets all requirements. -
Method Implementation (30%)
All required methods are implemented, includingaddGrade,getAverage,getLetterGrade, andprintReport. These methods properly access and modify instance variables. The logic within each method is clear and adheres to the problem requirements. -
Code Quality (20%)
The code is clean and well-structured. Variable names are meaningful, and the constructor is used effectively to initialize instance variables. Comments are included to explain the purpose of each method, making the code easy to understand and maintain. -
Output & Presentation (10%)
The output is clear and well-formatted. It includes grade reports for multiple students, showcasing different grades, averages, and letter grades. The presentation aligns with the rubric’s expectations.
Rationale for Grade (92%)
While the program meets all the requirements and the code is clean, there is always room for improvement. For example, additional edge case testing (e.g., handling negative grades or extremely high values) could further enhance the robustness of the program. Additionally, more detailed comments in complex sections of the code could improve clarity. Overall, the program fulfills the rubric criteria effectively, justifying the self-grade of 92%.