4 min read•Last Updated on June 18, 2024
Avanish Gupta
Milo Chang
Avanish Gupta
Milo Chang
For the next couple of topics, we will focus on writing methods. The first type that we will consider are accessor methods. Accessor methods are methods that allow other clients (objects, classes, and users) to access the data of an object. Since we want other clients to access this, accessor methods are made public. There are two types of accessor methods:
On the other hand, the toString() method returns the information about an object as a string. This is usually done through string concatenation. As we will see when writing our toString() methods later in the section, we do not need to call the getter methods for specific instance variables. Even though the variables are private, they are in the class, so we can access these variables directly. If we try to print an object in another method, that object's toString() method is automatically called.
Now, we will write accessor methods for our two classes. Note that we do not write accessor methods for all our instance variables because we want some of them to stay private. This will be used with correctAnswer in the Assignment class and age in the Student class.
Note how we use @Override when we use toString(). We will learn about that in Unit 9!
/** Represents an assignment that a student will complete
*/
public class Assignment {
private boolean correctAnswer; // represents the answer to an assignment, either T/F
/** Makes a new assignment with one True/False question and sets the correct answer
*/
public Assignment(boolean answer) {
correctAnswer = answer;
}
**/** Prints details about the assignment
*/
@Override
public String toString() {
return "This is an assignment with correct answer " + answer;
}**
}
/** Represents a high school student
*/
public class Student {
private int gradeLevel; // a grade between 9-12
private String [name](https://www.fiveableKeyTerm:name); // the students name in the form "FirstName LastName"
private int age; // the student's age, must be positive
private Assignment assignment; // the current assignment the student is working on
/** Makes a new student with grade gradeLev, name fullName, and age ageNum
*/
public Student(int gradeLev, String fullName, int ageNum) {
gradeLevel = gradeLev;
name = fullName;
age = ageNum;
assignment = null; // There is no active assignment at the moment
}
**/** Returns the student's grade level
*/
public int getGradeLevel() {
return gradeLevel;
}
/** Returns the student's name
*/
public String getName() {
return name;
}
/** Returns the current assignment the student is working on
*/
public Assignment returnCurrentAssignment() {
return assignment;
}
/** Prints details about the student
*/
@Override
public String toString() {
return name + ", a " + gradeLevel + "th grade high school student";
}**
}
It is important to note the return types of the getter methods we write; these methods are non-void since we want them to return a value. The return type of a specific getter method is the same type as the instance variable whose value we want to get.
When the getter method has to return a reference to an object, a copy of that reference is returned, not a copy of the object.
Once the return keyword is triggered in a method, the program immediately returns to the point after whatever called the method.
To see this control flow in action, let's look here. Assume that this is in the main method of some other class:
System.out.println("Starting the example.");
Student bob = new Student(10, "Bob Smith", 16);
System.out.println(bob);
System.out.println("End of example.");
First, the program in the main method will print out "Starting the example."
Next, the program in the main method will create an instance of the Student class by using the Student constructor. It will initialize gradeLevel to 10, name to "Bob Smith," age to 16, and assignment to null. With the creation of this object, the computer will move on to the next line of the main method.
To print out bob, the program in the main method will use the toString() method of the Student class, which will return a String ("Bob Smith, a 10th grade high school student") that will then be printed.
Lastly, the program in the main method will print out "End of example."
The @Override annotation is used in Java to indicate that a method in a subclass is intended to override a method with the same name in its superclass. It helps ensure that the method signature and return type are correct.
Term 1 of 15
The @Override annotation is used in Java to indicate that a method in a subclass is intended to override a method with the same name in its superclass. It helps ensure that the method signature and return type are correct.
Term 1 of 15
The @Override annotation is used in Java to indicate that a method in a subclass is intended to override a method with the same name in its superclass. It helps ensure that the method signature and return type are correct.
Term 1 of 15
Accessor methods, also known as getter methods, are a type of method in object-oriented programming that allows the retrieval of the value of an object's private data member. They provide read-only access to the internal state of an object.
Getter Methods: Getter methods are a specific type of accessor method that retrieves the value of a specific attribute or property of an object.
Setter Methods: Setter methods, also known as mutator methods, allow modification or update to an object's private data members.
Encapsulation: Encapsulation is a principle in OOP that combines data and functions into a single unit called an object, where data is hidden from external access and can only be accessed through defined public interfaces (such as accessor and mutator methods).
Public is an access modifier in Java that indicates unrestricted visibility for classes, methods, and variables. Public members can be accessed from any other class or package.
Private: Private is an access modifier that restricts visibility to only within the same class. Private members cannot be accessed from outside the class.
Protected: Protected is an access modifier that allows visibility within the same package or subclasses. Protected members are not accessible from unrelated classes.
Default (package-private): Default, also known as package-private, is an access level without any keyword specified. It allows visibility within the same package but not outside of it.
An instance variable is a variable that belongs to an object and holds unique data for each instance of the class. It is declared within a class but outside any method.
Class Variable: A class variable is a variable that belongs to the entire class rather than individual instances. It is shared among all instances of the class.
Local Variable: A local variable is a variable that is declared and used within a specific method or block of code. It exists only within that scope.
Global Variable: A global variable is a variable that can be accessed from anywhere in the program, regardless of scope or location.
A return statement is used in functions/methods to specify what value should be sent back as output when the function is called. It terminates the execution of a function and returns control back to where it was called from.
Function: A function is a block of code that performs a specific task. It can have input parameters and may or may not return a value.
Method: A method is similar to a function but is associated with an object or class in object-oriented programming.
Void: Void is used as a return type for functions/methods that do not return any value.
The return type in programming refers to the data type of the value that a method or function will return when it is called. It specifies what kind of data will be returned by the method.
Method Name: The name given to a method or function which helps identify and call it within a program.
Parameters: Inputs or arguments passed into a method or function for it to perform its task.
Data Type: Specifies the type of data that can be stored in a variable, such as integer, string, boolean, etc.
String concatenation is the process of combining two or more strings together into one longer string. It is achieved using the "+" operator in most programming languages.
String interpolation: A method of constructing new strings by embedding expressions inside string literals.
Concatenation assignment operator (+=): A shorthand way of appending one string to another.
Immutable strings: Strings that cannot be modified once created.
A correct answer refers to the accurate response to a question or problem in a given context.
Incorrect Answer: An incorrect answer refers to a response that is not accurate or does not match the expected solution.
Multiple Choice Question: A multiple choice question is a type of question where several options are provided, and one must select the correct answer from those options.
True/False Question: A true/false question is a type of question where one must determine whether a statement is true or false.
An assignment class refers to a class used to store values assigned to variables. It is commonly used in programming to hold and manipulate data.
Variables: These are named memory locations that store values. They are often associated with specific data types and can be assigned new values using assignment classes.
Data Types: In programming, each variable has a specific data type that determines the kind of values it can hold. Assignment classes help manage these different data types.
Object-Oriented Programming (OOP): OOP is a programming paradigm that uses objects and classes to structure code. Assignment classes play a crucial role in implementing OOP concepts by storing object instances and their associated data.
A student class is a blueprint or template that defines the properties and behaviors of a student object. It specifies what data (such as name, grade level) and methods (such as calculateGPA()) a student object can have.
gradeLevel: The gradeLevel is a data property of the student class that represents the academic year or level of the student.
name: The name is a data property of the student class that represents the personal identification of the student.
calculateGPA(): The calculateGPA() method is one behavior defined in the student class that calculates and returns the Grade Point Average (GPA) of the student based on their grades.
The @Override annotation is used in Java to indicate that a method in a subclass is intended to override a method with the same name in its superclass. It helps ensure that the method signature and return type are correct.
Inheritance: Inheritance is when one class inherits properties and behaviors from another class. For example, a Dog class can inherit traits from an Animal class.
Polymorphism: Polymorphism allows objects of different classes to be treated as objects of the same parent class. It enables flexibility and reusability in code.
Method Overloading: Method overloading occurs when multiple methods have the same name but different parameters. This allows you to perform similar operations with different inputs.
A student constructor is a specific type of constructor used to create objects representing students. It initializes instance variables related to student attributes such as name, age, grade level, etc., when creating new student objects.
Object: An object is an instance of a class that encapsulates data and methods related to that class.
Instance Variables: Instance variables are non-static variables declared within a class. Each instance (object) of the class has its own copy of these variables.
Class: A class is a blueprint or template for creating objects. It defines the properties and behaviors that objects of that class will have.