Using Objects:
8.1: Objects – Instances of Classes
Reference types hold references to objects which can be accessed from
memory.
Object = Instance of a class created in memory.
- Ex: String name = "My name is Karel."; 'name' = reference to a
String object.
- Objects are instances of classes, created using ‘new’ or literals.
- A reference variable points to the memory location of an object.
- Objects contain both state (instance variables) and behavior
(methods).
Class = Template for creating objects and what their state and behavior can
be.
- Ex: Class is the blueprint of a house while the object is the actual
house.
‘new’ = Used to create new objects from a class.
Literals = Fixed values directly written in code to represent specific values of
primitive types, strings, or other constant data types. They are the actual
values assigned to variables.
- Literal Types = ‘int’, ‘double’, ‘char’, ‘boolean’, ‘String’, and ‘null’.
o ‘null’ = Represents the absence of a value or reference.
State (Instance Variables) = Variables belonging to a specific instance
(object) of a class and store the data defining state of that object.
- Object’s attributes or characteristics.
- Declared within the class, but outside any method or constructor.
- Each object has its own copy of instance variables.
- They represent the data or properties associated with the object.
- The object's state is defined by the values of its instance variables.
- Ex: The state of ‘myCar’ is ‘color = “Red”;’ and ‘speed = 100;’
Behavior = Actions / functions that can be performed on the object.
- Typically represented by methods within the class, they often
interact / use the object's state (instance variables).
- Ex: Actions such as finding the area and perimeter of a rectangle would
need its width and height which is considered the rectangles state.
Method = Block of code that performs a specific task and is part of a class.
- Used to define the behavior of objects and can be called to perform
actions, compute values, or manipulate the object's state.
- Can be called any time after the object is created.
Constructor = Special method used to initialize an object when it is created,
having the same name as the class.
- Called only once when an object is first created.
While the constructor sets
up the object, methods
define its behavior.
Methods don't depend on
constructors to work, but
an object must be properly
constructed (with the
constructor) before its
methods can be used.
Ex:
1. Class: The Blueprint
The class keyword defines a blueprint called Rectangle. This blueprint
outlines the common features and behaviors that all rectangles will
have.
2. Object: The Instance
The new keyword creates a specific instance of the Rectangle class,
named ‘myRectangle’. This is like creating a real rectangle on your
canvas.
3. State: The Rectangle's Properties
‘myRectangle’ will have ‘width’ and ‘height’ as instance
variables (properties) that store the dimensions of a specific rectangle.
Each Rectangle object will have its own
unique width and height values.
4. Behavior: What the Rectangle Can Do
‘area()’ and ‘perimeter()’ are methods (behaviors) that define what
a Rectangle object can do. They perform calculations based on the
object's state (its width and height).
5. Methods: The Actions' Code
The code within the ‘area()’ and ‘perimeter()’ methods define the exact
steps involved in calculating the area and perimeter, respectively.
6. Constructor: The Initializer
The ‘Rectangle(int width, int height)’ method is the constructor. It's
called automatically when you create a new Rectangle object. It
initializes the object's state (sets the width and height) based on the
values provided.
8.2: Creating and Storing Objects (Instantiation)
Instantiation = Process of creating an object from a class by calling the
class’s constructor, usually using the ‘new’ keyword.
Class implementation:
- A class must have a name and must be written in its own java file.
- Ex: [class Rectangle]’s file would be called [Link].
Instance Variable (State) implementation:
- After the class is implemented, establishing instance variables [IV]
comes after.
- When a new object is created, it will store its values in the IVs.
- Ex: [class Rectangle]’s instance variables are width and height.
- IVs are written with keyword ‘private’ to prevent access from outside
files.
Creating Constructor: Access Specifier + Class name + Parameter list +
Attributes
- Access Specifier = Determines who has access to use method when
writing classes & objects (ex: public / private).
- Attributes / Instance Variable = Initialized within the constructor.
- Parameter list = Formal parameters, includes data type and variable
name.
- Formal parameters = Used to initialize the instance variables of the
class.
Calling Constructor: Class name + Object name = new + Class name +
Parameter list
- Syntax: className objectName = new className();
- Object name = Used to address the object.
- ‘new’ = Used to instantiate a new class object.
- Parameter list = Actual parameters, includes real values /
expressions.
- Actual parameters = Values passed to the constructor, which must
match the formal parameters in type and number.
- Ex: Rectangle rect1 = new Rectangle(14, 16);
8.3: Storing Objects and Method Overloading
Further constructors can be made to improve flexibility & functionality of
programs.
- Ex: When a developer wants to create a square out of a Rectangle
class, a new constructor can be made to accept 1 value, indicating all
sides are equal.
- New constructors can be made to accept a different # of parameters.
Overloading = Multiple constructors with same name but different formal
parameters.
- Compiler knows which constructor to use by the signature list of
parameters.
Constructors can be made with no parameters (empty parenthesis).
- Creates object with values predetermined.
- Can be used when creating a lot of objects and not wanting to repeat
code.
Different ways the Constructor can be called in real time:
Ex: When creating the rectangle class, you can choose to add all of them or
only one of them to the class to allow multiple ways to create a new
rectangle object.
‘null’ = object isn’t instantiated, it isn’t pointing to any particular object data.
- Keyword value indicating that a reference object doesn’t point to any
data.
- Used to find errors in code, and indicate an object isn’t referenced
properly.
Existing classes and libraries can be used in programs. An example of this is
the ‘Scanner’ class, which when used, means the user is a ‘client’ of that
class.
- When creating a new Scanner, we were instantiating a new scanner
object in order to read text which was input into the console.
- ‘([Link])’ = Actual Parameter | ‘(InputStream source)’ = Formal
Parameter
8.4: Calling a Void Method
Methods are procedures that allow us to control and define behavior of
objects.
Instance Method = Piece of code called on a specific instance (an object) of
the class.
Method Declaration:
Signature = Access Specifier + Return type + Method name +
Parameter list
- Signature = Information about how the method will function.
- Access Specifier = Determines who has access to use method when
writing classes & objects (ex: public / private).
- Return type = Indicates what ‘type value’ is returned from the method.
o Void method type means nothing is returned to the program.
- Method name = Same as naming a variable.
- Parameter list = Parameters are used to manipulate objects & data.
o An empty parameter list means they aren’t needed for the
function.
o The values used will be from the instance variables.
Method Ex – Void Method:
Using / Calling a method =
[Link]();
Non-static method = Method
excluding keyword ‘static’.
Not instantiating objects that have
been declared will cause a
‘NullPointerException’.
Void methods cannot be assigned to a variable of any other type.
Method Ex: [Link](); & [Link]();
- Scanner methods can be assigned to variables String text =
[Link]();
8.5: Calling a Void Method with Parameters
Methods can have formal parameters that affect the state of the object.
- Value of parameters must match data type.
- Ex: Value of printArea changed 50 30 due to change in width.
Methods can also be overloaded similar to constructors:
Method Overloading:
- Method overloading allows a class to have multiple methods with the
same name but different parameter lists (type, number, or both).
- Example: A Printer class that can print different types of data.
Encapsulation:
- Practice of bundling data and methods into a class while restricting
direct access to the data using access modifiers (ex: ‘public’ and
‘private’).
Polymorphism:
- Polymorphism allows methods to perform differently based on the
object that it is acting upon, usually through method overriding in a
class hierarchy.
- Ex: In a payment processing system, different payment methods such
as Credit Card, Debit Card, and PayPal all use a common
processPayment() method, allowing for uniform handling of various
payment types.
‘public String toString()’ = Method used to represent an object through a
string/text.
Accessor = Gets or retrieves the value of a private field.
- Getter = Type of accessor; retrieves a private field value without
modifying.
Mutator = Sets or modifies the value of a private field.
- Setter = Type of mutator; modifies a private field value, usually w/
validation.
8.6: Calling a non-Void Method
Return type = Determines the type that will be returned from a method.
- Return a value from a method by using keyword ‘return’.
‘return’ = Keyword allowing system to return a variable / value back into the
existing program allowing it to be used further along in the program.
- Using return statement makes the method more useful.
Ex: The value associated with ‘area’ can be used in many ways.
A method with a return type has multiple functionalities:
- Can store value of a method in other variables or be used in other
expressions.
Ex: Variable ‘area’ holds the value of 20 which it got from the return
statement.
- Although the 2 variables ‘area’ share the same value at this time, they
are not the same variable.
- ‘newArea’ holds value of 20 from ‘getArea()’ method, but ‘area’ still
has value of 10.
- If ‘area’ was initialized to hold a value of 10, when ‘area’ is printed,
even after calling printArea, the value printed in the last line is 10.
o ‘area’ variable in the code editor is different from the method
‘area’
- Once the method is finished executing, the ‘area’ variable inside the
method doesn’t exist anymore in the program. This is called ‘scope’.
The ‘return’ data type used in method signature must match the type being
returned.
- Ex: If return type is ‘String’, then the value being returned must match
it.
o Not doing so will cause an error in the program.
Ex: How many 13 x 7 desks could fit in a 200 x 114 space?
- Step 1: Find total area of the space.
- Step 2: Find area of a desk.
- Step 3: Divide total area by desk area.
- Step 4: Print the number of desks the space could fit.
8.7: String Objects
When a data type starts capitalized, that means it’s a Reference type.
- Strings are objects, so
they can be written as a
constructor too.
- Since strings are objects, they can also have methods associated with
them.
List of few String Methods:
String Methods don’t alter existing Strings but create new ones as they are
‘immutable’.
- Immutable = Once created, Strings cannot be changed.
- Only way to change value of a String is to reassign it.
String Method
‘toUpperCase’ assigns
value of ‘name’ to a
new variable and
making it fully
capitalized.
String ‘name’ is
reassigned from karel
to Bob and is printed.
Strings can be ‘concatenated’ with another to create a new String value.
- Concatenation = Process of adding 2 string values together.
- Written using the ‘+’ sign.
- Have to add space between string values to account for how it’s
printed.
- Shortcut ‘+=’ can be used to assign String objects with additional
values.
- Primitive values / types can be concatenated with String objects.
o Implicit Conversion = Primitives are automatically converted to
String objects when they are concatenated with a String.
- Equations in brackets ensure that int’s are added before
concatenation:
String dilemma:
- Quotation marks are used to identify the characters and values of a
String.
o Writing quotes directly into the program causes an error as
writing quotes directly into the program is interpreted as actual
String values.
- Using [\”] (backslash), we can include the quotation character in the
String.
o [\”] is an example of an ‘escape sequence’.
o 2 [\”] are included for both the quotations surrounding ‘Thank
You!’.
- Escape Sequence = Series of characters allowing inclusion of special
characters/actions in String objects.
o All escape sequences start with a backslash [\].
8.8: