πŸ“š

Β >Β 

πŸ’»Β 

Β >Β 

πŸ“±

Unit 2 Overview: Using Objects

10 min readβ€’june 18, 2024

Kashvi Panjolia

Kashvi Panjolia

Avanish Gupta

Avanish Gupta


AP Computer Science AΒ πŸ’»

130Β resources
See Units

The Big Takeaway Of This Unit

πŸ’‘Objects Objects are instances of classes and we can write methods to manipulate these objects.

Unit Overview

Exam Weighting

  • 5-7.5% of the test
  • Roughly 2 to 3 multiple-choice questions

Enduring Understanding

Java is what is known as an object-orientated programming language, or OOP for short. What is this object-orientated programming, and why is it so important to Java? This is the first of three units emphasizing object-orientated programming (the others are Units 5 and 9, covering classes and inheritance respectively). This unit, we will be learning about objects, the cornerstone of object-orientated programming, and what they are. There are four principles of object-orientated programming: abstraction (partly covered in this unit, also in Unit 5), encapsulation (covered in Unit 5), inheritance, and polymorphism (both covered in Unit 9).

Building Computational Thinking

In this unit, you'll learn how to write your first methods (functions in other programming languages), which perform a specific class. You'll also learn how to use methods from the Math and String classes, which will allow us to work more with numbers and text. These will make the foundations of all future units. Finally, you'll learn about objects, which are reference types: combinations of other data types that allow us to represent actual items and situations.

Main Ideas for This Unit

  • Making/Initializing Objects
  • Writing/Calling Methods
  • String Class
  • String Methods
  • Wrapper Classes
  • Math Class

2.1: Objects: Instances of Classes

Java is an object-orientated programming language, which means that most major programs in Java are about the manipulation of objects. What are objects? Objects are a reference type, which refers to how they are combinations of other primitive and reference data types. When you refer to them, you are not referring to the actual object itself, but where it is stored in data.
How do we know what combination of primitive and reference types each object has? This is due to the help of a class. A class is like a template that defines what an object is like and what the object can do. A class is basically the guidelines for a type of object, and an object is a particular instance of that class. We can think of a class as a blueprint for a house, and the object is a particular house. Different houses are different objects. The different houses may look different, but they have the same general features and functions. This is how classes and objects work.

2.2 Creating and Storing Objects (Initialization)

To create an object, we call the object's constructor. Every class must have a constructor, and if you do not create one, it will have a default constructor that is empty. If we use the analogy that a class is like a blueprint for an object, the constructor, when called, is the architect that makes the blueprint come to life. The constructor takes in parameters, which are the attributes of the object (name, age, etc), and when called, those parameters can be assigned specific values to create the object. Here is an example constructor and initialization of a car object:
Car(String brand, String model, int year) Car flash = new Car("BMW", "X7", 2023);
Creating an object is similar to creating a variable: you start with the type, then enter the name of the object, and use the equals sign (assignment operator) to assign the object to a value. With objects, however, the "new" keyword is used to create a new object. It is important you include this keyword when you initialize objects; otherwise, you will simply point the object you created to another object.
Notice how the brand, model, and year were provided in the order they were written in the constructor. When calling methods and constructors, the order of the parameters matters. An IllegalArgumentException will arise if you enter the order of the parameters differently than they were provided in the constructor. In this case, the constructor stated the order needs to be (String, String, int), so if you entered (String, int, String), the program would crash, and this exception will display. The computer will not know what to do if you enter the parameters in a different order.
A class can have multiple constructors. This is called overloading a constructor. Each constructor must be different than the others. Since the constructor must only be named the name of the class, the constructors should be differentiated based on their parameters.
Null is another keyword in Java. You can instantiate an object as null, meaning there is no reference created and the object contains nothing. Here's how to do it:
Car lightning = null;
Be careful when you instantiate an object as null, because if you try to call a method on it or use it anywhere else, you will get a NullPointerException. This is an important exception, and it states that the computer cannot do anything with this object because, well, there is no reference to the object.
https://i.imgflip.com/697yyj.jpg

Image courtesy of IMGFlip.

2.3 Calling a Void Method

A method is made up of five main parts: the scope, the return type, the name, the parameters, and the body. This may sound like a lot, but it's very formulaic. We'll tackle methods with this example:
public void study(int hoursStudied) {
totalHours += hoursStudied;
}
The first word, public, defines the scope of the method. Public means that anyone that accesses your code after it has been published can see this method. The next word, void, defines the return type of the method. Void means the method returns nothing. The name of the method is study, and it is case-sensitive.
This method only has one parameter: hoursStudied, which is an int. When this method is called, the user will have to enter an integer defining the number of hours they studied for. Finally, the body of the method is the statement totalHours++; and it tells the computer what the method does. There may be a variable elsewhere in the class called totalHours that is being incremented by the amount of hoursStudied every time the method is called.
This method can be called on an object. Person bob = new Person("bob");
bob.study(2);
In this snippet, a new object of type Person was created, and the name parameter was passed in as "bob." Then, the study method was called on bob using dot notation. Dot notation is the usage of a period, or dot, to call a method on an object. The number of hours bob studied was 2 hours, so 2 was passed in as an argument to the study method.
https://demmelearning.com/wp-content/uploads/2018/09/6-Reasons-Why-We-Learn-Algebra.jpg

How you feel after writing your first method in Java. πŸ‘ Image courtesy of DemmeLearning.

2.4 Calling a Void Method with Parameters

Methods, like constructors, can be overloaded. This means the parameter list for each method that is overloaded must be different.
public void waterTracker(int numberOfGlasses)
public void waterTracker(String typeOfDrink)
The method waterTracker is overloaded because there are two methods with the same name. However, these two methods are still different because the first one takes an integer as a parameter and the second one takes a String as a parameter. Depending on what you pass in as the argument when called the waterTracker method, one of these two methods will be called. Remember to stay hydrated.🚰

2.5 Calling a Non-Void Method

In the study(int hoursStudied) method defined above, the return type was void, so nothing was returned. However, there are many different return types for methods in Java, and they can be both primitive and reference types. A method can return an int, String, boolean, double, Object, and other types of data. Implementing a non-void return type in a method is useful when we want to store the result of the method for later.
Each method that has a non-void return type must have a return statement at the end of the method. A return statement will tell the computer what is being returned by that method and will be the data we will store for later. The return statement must always be the last line in the method.
public double degreesToRadians(double degrees) {
double radians = degrees * (3.141 / 180);
return radians;
} In this method, the return type of the degreesToRadians method is a double, so we return the variable radians because it is a double. We can now store the value returned by this method in a variable like this:
double result = degreesToRadians(34.5); The right side of the expression will evaluate to approximately 0.602, which will then become the value of the variable result. Pretty useful!

2.6 String Objects: Concatenation, Literals, and More

In Java, a String object is a sequence of characters. You can create a String object by using the String class's constructor.
String greeting = new String("What's up?");
However, the more efficient version is to use a string literal, which you learned about in the previous unit.
String greeting = "What's up?";
Since a String is an object, you can call methods on Strings like you would for any other object. Some common methods are .length() and .toLowerCase(). One special attribute of Strings is string concatenation. String concatenation is the process of combining two or more strings into a single string. You can concatenate strings using the + operator. Be sure to add a space between words because Java will not do that for you.
String greeting = "What's " + "up?";
Escape characters are characters that are used to represent certain special characters in a string. For example, the \n escape character is used to represent a new line in a string. Here is an example of a string with an escape character:
String greeting = "Hello,\nworld!";
This will output: Hello,
world!

2.7 String Methods

In Java, the String class has several methods that can be used to perform operations on strings. Some common String methods are:
  • length(): This method returns the length of the string.
  • indexOf(String str): This method returns the index of the first occurrence of the specified string in this string.
  • substring(int beginIndex): This method returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the end of the string.
  • substring(int beginIndex, int endIndex): This method returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.
As you can see, the substring method is an overloaded method and has two versions. The index of a string starts at 0 and counts every character, including spaces and punctuation marks. The reason the index starts at 0 and not 1 is that Java is a zero-indexed language. The string "taco cat" has a length of 8 characters, or 8 indices, by starting at 0 and counting each letter until the end of the string.

2.8 Using the Math Class

The Math class is a class in Java that provides various mathematical functions and constants. You do not need to import this class; it is already included in the standard Java package. Some common methods of the Math class are:
  • abs(int a): This method returns the absolute value of the argument as an int or double, depending on whether you put in an int or double into the argument.
  • pow(double a, double b): This method returns the value of a raised to the power of b as a double.
  • sqrt(double a): This method returns the square root of the argument as a double.
  • random(): This method returns a random number between 0 (inclusive) and 1 (exclusive) as a double.
  • The Math class also has constants you can use to increase your efficiency, such as Math.PI (approximately 3.14159).
    • 5-7.5% of the AP exam
    • Roughly 2 to 3 multiple-choice questions
    • Making/Initializing Objects
    • Writing/Calling Methods
    • String Class
    • String Methods
    • Wrapper Classes
    • Math Class
    https://demmelearning.com/wp-content/uploads/2018/09/6-Reasons-Why-We-Learn-Algebra.jpg
    • length(): This method returns the length of the string.
    • indexOf(String str): This method returns the index of the first occurrence of the specified string in this string.
    • substring(int beginIndex): This method returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the end of the string.
    • substring(int beginIndex, int endIndex): This method returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.
    • abs(int a): This method returns the absolute value of the argument as an int or double, depending on whether you put in an int or double into the argument.
    • pow(double a, double b): This method returns the value of a raised to the power of b.
    • sqrt(double a): This method returns the square root of the argument as a double.
    • random(): This method returns a random number between 0 (inclusive) and 1 (exclusive) as a double.


    Fiveable
    Fiveable
    Home
    Stay Connected

    Β© 2024 Fiveable Inc. All rights reserved.


    Β© 2024 Fiveable Inc. All rights reserved.