Unit 2 - Using Objects
Using Objects
- Instances of Classes
- Initializing Objects
- Calling a Void Method
- Calling a Void Method with Parameters
- Calling a Non-Void Method
- String Objects: Concatenation, Literals, and More
- String Methods
- Using the Math Class
- Hacks
Instances of Classes
Java is an object-oriented programming language, focusing on the manipulation of objects. Objects are a reference type, meaning they combine primitive and reference data types. When referenced, it points to their storage location.
The composition of each object is defined by a class, which acts as a template. A class outlines what an object is and what it can do, similar to a blueprint for a house. Each house (object) built from this blueprint (class) may vary in appearance but shares common features and functions.
Initializing Objects
To create an object, we call the object’s constructor. Every class must have a constructor; if you don’t create one, a default empty constructor is provided. If a class is like a blueprint, the constructor is the architect bringing it to life. The constructor takes in parameters (e.g., name, age) and assigns specific values to create the object.
Example:
Car(String brand, String model, int year)
Car flash = new Car("BMW", "X7", 2023);
Creating an object is similar to creating a variable: start with the type, enter the object’s name, and use the equals sign (assignment operator) to assign a value. Use the new keyword to create a new object. The order of parameters in the constructor matters; an IllegalArgumentException will arise if the order is incorrect.
A class can have multiple constructors (overloading), differentiated by their parameters.
The null keyword means no reference is created, and the object contains nothing:
Car lightning = null;
Be cautious with null objects, as calling a method on them results in a NullPointerException.
Calling a Void Method
A method consists of five main parts: scope, return type, name, parameters, and body. Here’s an example:
public void study(int hoursStudied) {
totalHours += hoursStudied;
}
- Scope:
public
- Anyone can access this method. - Return type:
void
- The method returns nothing. - Name:
study
- Case-sensitive. - Parameters:
int hoursStudied
- Requires an integer input. - Body:
totalHours += hoursStudied;
- The method’s action.
This method can be called on an object:
Person bob = new Person("bob");
bob.study(2);
In this snippet:
- A new Person object named bob is created.
- The
study
method is called on bob using dot notation. 2
is passed as an argument, indicating bob studied for 2 hours.
Calling a Void Method with Parameters
Methods, like constructors, can be overloaded, meaning each method has a different parameter list.
Example:
public void waterTracker(int numberOfGlasses)
public void waterTracker(String typeOfDrink)
The waterTracker
method is overloaded with two versions:
- Takes an integer parameter.
- Takes a String parameter.
Depending on the argument passed when calling waterTracker
, the appropriate method is invoked.
Calling a Non-Void Method
In the study(int hoursStudied)
method, the return type was void, meaning nothing was returned. However, methods in Java can have various return types, both primitive and reference types. Methods can return types like int, String, boolean, double, Object, and more. Implementing a non-void return type allows storing the result for later use.
A method with a non-void return type must end with a return statement, specifying what the method returns. The return statement must be the last line in the method.
Example:
public double degreesToRadians(double degrees) {
double radians = degrees * (3.141 / 180);
return radians;
}
In this method, the return type is double, so we return the variable radians. The result can be stored in a variable like this:
double result = degreesToRadians(34.5);
The right side evaluates to approximately 0.602, which becomes the value of result. Pretty useful!
String Objects: Concatenation, Literals, and More
In Java, a String object is a sequence of characters. You can create a String object using the String class’s constructor:
String greeting = new String("What's up?");
However, the more efficient way is to use a string literal:
String greeting = "What's up?";
Since a String is an object, you can call methods on it, such as .length()
and .toLowerCase()
. One special feature of Strings is string concatenation, which combines two or more strings into a single string using the +
operator. Remember to add a space between words, as Java does not do that automatically:
String greeting = "What's " + "up?";
Escape characters represent special characters in a string. For example, \n
represents a new line:
String greeting = "Hello,\nworld!";
This will output:
Hello,
world!
String Methods
In Java, the String class has several methods for performing operations on strings. Some common String methods are:
- length(): Returns the length of the string.
- indexOf(String str): Returns the index of the first occurrence of the specified string.
- substring(int beginIndex): Returns a new string that starts at the specified beginIndex and extends to the end of the string.
- substring(int beginIndex, int endIndex): Returns a new string that starts at beginIndex and extends to endIndex - 1.
The substring method is overloaded with two versions. In Java, indexing starts at 0, meaning the first character of a string has an index of 0. For example, the string "taco cat"
has a length of 8 characters, with indices from 0 to 7.
String test = "test";
System.out.println(test.length());
System.out.println(test.indexOf("es"));
System.out.println(test.substring(2));
System.out.println(test.substring(2, 3));
4
1
st
s
Using the Math Class
The Math class in Java provides various mathematical functions and constants. It’s included in the standard Java package, so no import is needed. Some common methods of the Math class are:
- abs(int a): Returns the absolute value of the argument as an int or double, depending on the input type.
- pow(double a, double b): Returns the value of a raised to the power of b as a double.
- sqrt(double a): Returns the square root of the argument as a double.
- random(): Returns a random number between 0 (inclusive) and 1 (exclusive) as a double.
The Math class also includes constants like Math.PI (approximately 3.14159).
Summary of Topics
- Making/Initializing Objects
- Writing/Calling Methods
- String Class
- String Methods
- length(): Returns the length of the string.
- indexOf(String str): Returns the index of the first occurrence of the specified string.
- substring(int beginIndex): Returns a new string that starts at beginIndex and extends to the end.
- substring(int beginIndex, int endIndex): Returns a new string that starts at beginIndex and extends to endIndex - 1.
- Wrapper Classes
- Math Class
- abs(int a): Returns the absolute value of the argument.
- pow(double a, double b): Returns a raised to the power of b.
- sqrt(double a): Returns the square root of the argument.
- random(): Returns a random number between 0 and 1.
Additional Resources:
Hacks
Part 1
public class Car {
String brand;
String model;
int year;
boolean isElectric;
public Car(String brand, String model, int year, boolean isElectric) {
this.brand = brand;
this.model = model;
this.year = year;
this.isElectric = isElectric;
}
public void printCarInfo() {
System.out.println("Brand: " + brand + ", Model: " + model + ", Year: " + year + ", Electric: " + isElectric);
}
public boolean isElectricCar() {
return isElectric;
}
}
public static void main(String[] args) {
Car car1 = new Car("Tesla", "Model S", 2023, true);
Car car2 = new Car("Ford", "Mustang", 2022, false);
Car car3 = new Car("Nissan", "Leaf", 2023, true);
car1.printCarInfo();
System.out.println("Is car2 electric? " + car2.isElectricCar());
}
Answer the following questions based on the code above:
- a) What is the purpose of the
Car
class in the given code? How does it represent the concept of objects in Java? - Answer:
- b) Explain how the
printCarInfo
method is used in the code. What information does it display, and how is it called? - Answer:
- c) The method
isElectricCar
returns a boolean value. Explain how this method is used with thecar2
object and what the output will be. - Answer:
- d) If you wanted to add a new method to the
Car
class to calculate the car’s age, how would you implement it? Provide a brief code example. - Answer:
Part 2
Situation: You are building an inventory management system where you need to manage different products. Each product has attributes like name, quantity, and price.
(a) Define the term “class” in Java and explain how it relates to objects. Provide an example to illustrate your explanation.
(b) Explain the purpose of a constructor in a Java class. How does it differ from a method?
(c) Code:
You need to create a Product
class with attributes String name
, int quantity
, and double price
. Write a constructor for this class that initializes these attributes. Also, write a method calculateTotalValue
that returns the total value of the product (quantity * price). Provide comments in your code to explain each step.