Browse By Unit
12 min read•june 18, 2024
Kashvi Panjolia
Kashvi Panjolia
This unit makes up 5-7.5% of the AP exam, and FRQ #2 requires you to write a class from scratch. Learning how to write a class opens up many doors to creating programs that solve a variety of problems. You could write a class to simulate a candy store, with methods for the cart and converting candies to their prices; a class to create a calculator interface that can solve more than just your average calculator, with methods for the Pythagorean theorem and the area of a trapezoid; and even a class to simulate a bank account, with variables for the balance and account holder name, and methods to withdraw or deposit money. This guide will give you an overview of the important components of writing a class.
A class is a blueprint for the objects of that class. A class contains variables and methods to store and manipulate information. To create a class, you first state whether you want it to be public or private, use the class
keyword, and name the class. Then, you add a set of curly braces {}
that will contain the contents of the class. To understand the key components of classes, we will create an AreaCalculator
class. This is the class header:
public class AreaCalculator {}
Inside the curly braces, you can define the variables and methods of the class. Variables are used to store data, and methods are used to perform actions. In the AreaCalculator
class, we can create an instance variable to store the number of shapes a user has asked to calculate the area for:
public class AreaCalculator {
private int numShapes;
}
We made this variable private because other classes in this program will not need to access this variable. For the most part, instance variables will be private. The class itself, however, needs to be public so other classes can create an object of the AreaCalculator
.
Notice how we only declared the variable numShapes
, but we haven't initialized it yet. To initialize instance variables, we need to create a constructor. A constructor in Java is a special method that is used to create and initialize an object of that class. Every class must have at least one constructor, and you can define additional constructors as well. If you do not define a constructor for your class, a default one will be created.
A constructor has the same name as the class, and it does not have a return type. Constructors should be made public so objects of a class can be created in other classes. Inside a constructor, we can initialize the numShapes
instance variable.
public class AreaCalculator {
private int numShapes;
public AreaCalculator() {
numShapes = 0;
}
}
A constructor can take in parameters as well. It was not necessary to take in a parameter for this example, but here is an example of how constructor parameters are used to initialize the instance variables:
public class Car {
private String brand;
private String model;
private int year;
public Car (String make, String carModel, String yearMade) {
brand = make;
model = carModel;
year = yearMade;
}
}
In this example, the parameters of the constructor are being assigned to the instance variables to initialize the instance variables.
Other people who read your class, such as your teacher or your friends, may not understand what the variables and methods in your class are for. That's why it's important to document your code with comments. A comment is a piece of text that the computer will not recognize as code and will not try to execute. It's only there for the humans to read. While you can write whatever you want inside a comment, you should stick to explaining what your code does to document it properly.
There are three ways in Java to create a comment:
// Using these two slashes will create a single-line comment.
/* Using the slash and an asterisk
will create a multi-line comment
for longer explanations. Be sure to
close it with an asterisk, then a slash. */
/** Using the slash and two asterisks will create a
Java API documentation comment. In these comments,
you can use tags to specify the parameters of a method
and the return values of the method. These comments aren't as important
for the AP CSA curriculum.
@param -- explanation of parameter
@return -- explanation of what the method returns */
Here is an example of using comments to document our code with the AreaCalculator class:
public class AreaCalculator {
private int numShapes;
// the constructor initializes the numShapes instance variable to 0
public AreaCalculator() {
numShapes = 0;
}
}
In Java, accessor methods (also known as getters) are methods that are used to retrieve the value of a private variable in a class. Since these methods are public, they can be used to retrieve the values of these variables in a different class. This is an accessor method we could write for the numShapes
instance variable in our AreaCalculator
class:
public int getNumShapes() {
return numShapes;
}
Accessor methods always have a return type because they are used to return the instance variable, and they are usually one-line methods.
A mutator method (aka setter method) is a method that mutates, or modifies, the value of an instance variable. These methods typically have a return type of void, and only update the value of the instance variable. In the Car class above, we can create a mutator method to change the year the car was manufactured.
public void setYear(int newYear) {
year = newYear;
}
This way, if we entered the year incorrectly when first creating the Car
object, we can use the setYear
method to update it.
Now, we can finish out our AreaCalculator class by writing methods to compute the area of a triangle, rectangle, and trapezoid. These methods will take in parameters, so we should remember the concept of pass-by-value from Unit 2. When a primitive type is passed to a method, a copy of that value is passed, so the actual variable in the other class is not changed if we modify the value of the parameter inside the method. However, when an object is passed into a method as a parameter, the method receives a copy of the reference to that object, not a copy of the object. This means that if you mutate an object inside the method, the changes will show up outside of that method. That's why it is a good programming practice to not modify objects inside methods.
Here is the method for finding the area of a triangle:
public double triangleArea(double base, double height) {
double area = (base * height) / 2;
numShapes++;
return area;
}
Don't forget that we need to increment the value of numShapes
by 1 to show that a user asked the AreaCalculator
to find the area of a shape. Try writing the rectangleArea
and trapezoidArea
methods on your own, then check below for the answers.
public double rectangleArea(double length, double width) {
double area = length * width;
numShapes++;
return area;
}
public double trapezoidArea(double base1, double base2, double height) {
double area = (base1 + base2) * height / 2;
numShapes++;
return area;
}
The methods and variables we created above for the AreaCalculator
class were created to be used by objects of that class. However, we don't really need to create an AreaCalculator
object to be able to use the class since there is no object-specific information we are storing. We can create static variables and static methods that work across all objects of the class, but we don't need to create an object to access them. This is the AreaCalculator
class when made static:
public class AreaCalculator {
private static numShapes;
// the constructor initializes the numShapes static variable to 0
public AreaCalculator() {
numShapes = 0;
}
// returns the numShapes static variable
public static int getNumShapes() {
return numShapes;
}
// calculates the area of a rectangle using the length and width
public static double rectangleArea(double length, double width) {
double area = length * width;
numShapes++;
return area;
}
// calculates the area of a triangle using the base and height
public static double triangleArea(double base, double height) {
double area = (base * height) / 2;
numShapes++;
return area;
}
// calculates the area of a trapezoid using the two bases and the height
public static double trapezoidArea(double base1, double base2, double height) {
double area = (base1 + base2) * height / 2;
numShapes++;
return area;
}
}
Notice that all we had to do was add the static keyword to the variables and methods before we told the computer what their type or return type was. Now, we can simply use the name of the class to call all these methods instead of having to create an object each time.
AreaCalculator.triangleArea(5.0, 3.0);
In the methods of the AreaCalculator
class where we computed the areas of the shapes, the same variable name area
was used to store the area of the shape. Why would the computer not throw an error for using the same name? Because of the scope of the variables.
The area
variables were all created inside their respective methods, which meant they only existed inside those methods, and were deleted by the computer once the method had ended. Therefore, the three area
variables never existed at the same time, and we were able to use the same name for all of them.
In programming, scope refers to the visibility and accessibility of variables, functions, and other elements of a program.
Scope can be divided into two categories: global scope and local scope.
Global scope refers to the visibility and accessibility of an element throughout the entire program. An element that is in global scope can be accessed from anywhere in the program. The numShapes
variable had a global scope because we were able to use it in all of the methods of the AreaCalculator
class.
Local scope refers to the visibility and accessibility of an element within a specific block of code. An element that is in local scope can only be accessed from within the block of code in which it is defined. The area
variable had a local scope because it was defined each method.
In many programming languages, including Java, variables and functions can have different levels of scope based on where they are defined. For example, in Java, variables defined within a method have local scope, while variables defined outside of any method have global scope.
Scope is an important concept in programming, as it determines where an element can be accessed and used. Understanding scope can help you write more organized and efficient code, and it can also help you avoid errors and conflicts when working with variables and functions.
In Java, the this
keyword refers to the current instance of an object. It is used to access the fields and methods of the current object from within the object's own methods.
Here is an example of how the this
keyword can be used in a Java class:
public class MyClass {
int x;
public void setX(int x) {
this.x = x; // "this" refers to the current object
}
}
In this example, the setX
method sets the value of the x
field for the current object. The this.x
notation is used to specify that the x
field of the current object should be modified, rather than a local variable named x
that might be defined within the method.
The this
keyword is also used to pass the current object as an argument to a method. For example:
public class MyClass {
int x;
public void setX(int x) {
this.x = x;
}
public void updateX(MyClass obj) {
obj.setX(this.x); // "this" is used to pass the current object as an argument
}
}
In this example, the updateX
method calls the setX
method on another object (obj
), passing the value of the x
field for the current object as an argument. The this.x
notation is used to specify the value of the x
field for the current object, and the this
keyword is used to pass the current object of MyClass
as an argument to the setX
method.
The this
keyword is a useful tool for disambiguating between fields and local variables with the same name, and for passing the current object as an argument to a method.
Computing systems have the potential to impact society and individuals in a number of ways, both positive and negative. Some of the ethical and social implications of computing systems include:
Privacy: As computing systems collect, store, and process increasing amounts of personal data, there is a risk that this data could be accessed or used in ways that violate an individual's privacy.
Security: Computing systems are vulnerable to cyber attacks, which can result in the loss of sensitive data, financial loss, and damage to an individual's or organization's reputation.
Inequality: The availability and accessibility of computing systems can vary, leading to digital divide and inequality in access to information and opportunities.
Censorship: Governments and other organizations may use computing systems to censor or restrict access to certain information or websites.
Dependence: The increasing reliance on computing systems in various aspects of society has the potential to create dependency and disruption if systems fail or are unavailable.
While programs are usually designed to achieve a specific purpose for the good of society, they may have unintended consequences. It is important for individuals, organizations, and societies to consider and address these implications in order to ensure the responsible and ethical use of computing technology.
<< Hide Menu
12 min read•june 18, 2024
Kashvi Panjolia
Kashvi Panjolia
This unit makes up 5-7.5% of the AP exam, and FRQ #2 requires you to write a class from scratch. Learning how to write a class opens up many doors to creating programs that solve a variety of problems. You could write a class to simulate a candy store, with methods for the cart and converting candies to their prices; a class to create a calculator interface that can solve more than just your average calculator, with methods for the Pythagorean theorem and the area of a trapezoid; and even a class to simulate a bank account, with variables for the balance and account holder name, and methods to withdraw or deposit money. This guide will give you an overview of the important components of writing a class.
A class is a blueprint for the objects of that class. A class contains variables and methods to store and manipulate information. To create a class, you first state whether you want it to be public or private, use the class
keyword, and name the class. Then, you add a set of curly braces {}
that will contain the contents of the class. To understand the key components of classes, we will create an AreaCalculator
class. This is the class header:
public class AreaCalculator {}
Inside the curly braces, you can define the variables and methods of the class. Variables are used to store data, and methods are used to perform actions. In the AreaCalculator
class, we can create an instance variable to store the number of shapes a user has asked to calculate the area for:
public class AreaCalculator {
private int numShapes;
}
We made this variable private because other classes in this program will not need to access this variable. For the most part, instance variables will be private. The class itself, however, needs to be public so other classes can create an object of the AreaCalculator
.
Notice how we only declared the variable numShapes
, but we haven't initialized it yet. To initialize instance variables, we need to create a constructor. A constructor in Java is a special method that is used to create and initialize an object of that class. Every class must have at least one constructor, and you can define additional constructors as well. If you do not define a constructor for your class, a default one will be created.
A constructor has the same name as the class, and it does not have a return type. Constructors should be made public so objects of a class can be created in other classes. Inside a constructor, we can initialize the numShapes
instance variable.
public class AreaCalculator {
private int numShapes;
public AreaCalculator() {
numShapes = 0;
}
}
A constructor can take in parameters as well. It was not necessary to take in a parameter for this example, but here is an example of how constructor parameters are used to initialize the instance variables:
public class Car {
private String brand;
private String model;
private int year;
public Car (String make, String carModel, String yearMade) {
brand = make;
model = carModel;
year = yearMade;
}
}
In this example, the parameters of the constructor are being assigned to the instance variables to initialize the instance variables.
Other people who read your class, such as your teacher or your friends, may not understand what the variables and methods in your class are for. That's why it's important to document your code with comments. A comment is a piece of text that the computer will not recognize as code and will not try to execute. It's only there for the humans to read. While you can write whatever you want inside a comment, you should stick to explaining what your code does to document it properly.
There are three ways in Java to create a comment:
// Using these two slashes will create a single-line comment.
/* Using the slash and an asterisk
will create a multi-line comment
for longer explanations. Be sure to
close it with an asterisk, then a slash. */
/** Using the slash and two asterisks will create a
Java API documentation comment. In these comments,
you can use tags to specify the parameters of a method
and the return values of the method. These comments aren't as important
for the AP CSA curriculum.
@param -- explanation of parameter
@return -- explanation of what the method returns */
Here is an example of using comments to document our code with the AreaCalculator class:
public class AreaCalculator {
private int numShapes;
// the constructor initializes the numShapes instance variable to 0
public AreaCalculator() {
numShapes = 0;
}
}
In Java, accessor methods (also known as getters) are methods that are used to retrieve the value of a private variable in a class. Since these methods are public, they can be used to retrieve the values of these variables in a different class. This is an accessor method we could write for the numShapes
instance variable in our AreaCalculator
class:
public int getNumShapes() {
return numShapes;
}
Accessor methods always have a return type because they are used to return the instance variable, and they are usually one-line methods.
A mutator method (aka setter method) is a method that mutates, or modifies, the value of an instance variable. These methods typically have a return type of void, and only update the value of the instance variable. In the Car class above, we can create a mutator method to change the year the car was manufactured.
public void setYear(int newYear) {
year = newYear;
}
This way, if we entered the year incorrectly when first creating the Car
object, we can use the setYear
method to update it.
Now, we can finish out our AreaCalculator class by writing methods to compute the area of a triangle, rectangle, and trapezoid. These methods will take in parameters, so we should remember the concept of pass-by-value from Unit 2. When a primitive type is passed to a method, a copy of that value is passed, so the actual variable in the other class is not changed if we modify the value of the parameter inside the method. However, when an object is passed into a method as a parameter, the method receives a copy of the reference to that object, not a copy of the object. This means that if you mutate an object inside the method, the changes will show up outside of that method. That's why it is a good programming practice to not modify objects inside methods.
Here is the method for finding the area of a triangle:
public double triangleArea(double base, double height) {
double area = (base * height) / 2;
numShapes++;
return area;
}
Don't forget that we need to increment the value of numShapes
by 1 to show that a user asked the AreaCalculator
to find the area of a shape. Try writing the rectangleArea
and trapezoidArea
methods on your own, then check below for the answers.
public double rectangleArea(double length, double width) {
double area = length * width;
numShapes++;
return area;
}
public double trapezoidArea(double base1, double base2, double height) {
double area = (base1 + base2) * height / 2;
numShapes++;
return area;
}
The methods and variables we created above for the AreaCalculator
class were created to be used by objects of that class. However, we don't really need to create an AreaCalculator
object to be able to use the class since there is no object-specific information we are storing. We can create static variables and static methods that work across all objects of the class, but we don't need to create an object to access them. This is the AreaCalculator
class when made static:
public class AreaCalculator {
private static numShapes;
// the constructor initializes the numShapes static variable to 0
public AreaCalculator() {
numShapes = 0;
}
// returns the numShapes static variable
public static int getNumShapes() {
return numShapes;
}
// calculates the area of a rectangle using the length and width
public static double rectangleArea(double length, double width) {
double area = length * width;
numShapes++;
return area;
}
// calculates the area of a triangle using the base and height
public static double triangleArea(double base, double height) {
double area = (base * height) / 2;
numShapes++;
return area;
}
// calculates the area of a trapezoid using the two bases and the height
public static double trapezoidArea(double base1, double base2, double height) {
double area = (base1 + base2) * height / 2;
numShapes++;
return area;
}
}
Notice that all we had to do was add the static keyword to the variables and methods before we told the computer what their type or return type was. Now, we can simply use the name of the class to call all these methods instead of having to create an object each time.
AreaCalculator.triangleArea(5.0, 3.0);
In the methods of the AreaCalculator
class where we computed the areas of the shapes, the same variable name area
was used to store the area of the shape. Why would the computer not throw an error for using the same name? Because of the scope of the variables.
The area
variables were all created inside their respective methods, which meant they only existed inside those methods, and were deleted by the computer once the method had ended. Therefore, the three area
variables never existed at the same time, and we were able to use the same name for all of them.
In programming, scope refers to the visibility and accessibility of variables, functions, and other elements of a program.
Scope can be divided into two categories: global scope and local scope.
Global scope refers to the visibility and accessibility of an element throughout the entire program. An element that is in global scope can be accessed from anywhere in the program. The numShapes
variable had a global scope because we were able to use it in all of the methods of the AreaCalculator
class.
Local scope refers to the visibility and accessibility of an element within a specific block of code. An element that is in local scope can only be accessed from within the block of code in which it is defined. The area
variable had a local scope because it was defined each method.
In many programming languages, including Java, variables and functions can have different levels of scope based on where they are defined. For example, in Java, variables defined within a method have local scope, while variables defined outside of any method have global scope.
Scope is an important concept in programming, as it determines where an element can be accessed and used. Understanding scope can help you write more organized and efficient code, and it can also help you avoid errors and conflicts when working with variables and functions.
In Java, the this
keyword refers to the current instance of an object. It is used to access the fields and methods of the current object from within the object's own methods.
Here is an example of how the this
keyword can be used in a Java class:
public class MyClass {
int x;
public void setX(int x) {
this.x = x; // "this" refers to the current object
}
}
In this example, the setX
method sets the value of the x
field for the current object. The this.x
notation is used to specify that the x
field of the current object should be modified, rather than a local variable named x
that might be defined within the method.
The this
keyword is also used to pass the current object as an argument to a method. For example:
public class MyClass {
int x;
public void setX(int x) {
this.x = x;
}
public void updateX(MyClass obj) {
obj.setX(this.x); // "this" is used to pass the current object as an argument
}
}
In this example, the updateX
method calls the setX
method on another object (obj
), passing the value of the x
field for the current object as an argument. The this.x
notation is used to specify the value of the x
field for the current object, and the this
keyword is used to pass the current object of MyClass
as an argument to the setX
method.
The this
keyword is a useful tool for disambiguating between fields and local variables with the same name, and for passing the current object as an argument to a method.
Computing systems have the potential to impact society and individuals in a number of ways, both positive and negative. Some of the ethical and social implications of computing systems include:
Privacy: As computing systems collect, store, and process increasing amounts of personal data, there is a risk that this data could be accessed or used in ways that violate an individual's privacy.
Security: Computing systems are vulnerable to cyber attacks, which can result in the loss of sensitive data, financial loss, and damage to an individual's or organization's reputation.
Inequality: The availability and accessibility of computing systems can vary, leading to digital divide and inequality in access to information and opportunities.
Censorship: Governments and other organizations may use computing systems to censor or restrict access to certain information or websites.
Dependence: The increasing reliance on computing systems in various aspects of society has the potential to create dependency and disruption if systems fail or are unavailable.
While programs are usually designed to achieve a specific purpose for the good of society, they may have unintended consequences. It is important for individuals, organizations, and societies to consider and address these implications in order to ensure the responsible and ethical use of computing technology.
© 2024 Fiveable Inc. All rights reserved.