Unit 5 - Writing Classes
Basics of Writing Classes and Using Objects
Objects are also referred to as instances of a class or simply instances. They encapsulate state (data) and behavior (methods).
Object-oriented programming languages: Java, C++, C#, Python. These languages facilitate the creation of reusable, modular, and maintainable code through the use of objects and classes.
What is an Object?
Objects possess:
States: Represented by fields in Java. These fields hold the data that defines the object's characteristics.
Behaviors: Represented by methods in Java. Methods define what an object can do.
Example: A dog object.
States: color, awake status, age. These are attributes of the dog.
Behaviors: bark, run, eat. These are actions the dog can perform.
States represented by fields; behaviors by methods. Fields store the state, while methods implement the behavior.
What is a Class?
A class is a blueprint or template for creating objects. It defines the structure and behavior that objects of that class will have.
Static Methods:
Behaviors that can be accessed directly from the class without creating an object. They operate on the class itself rather than on instances.
Identified by the
statickeyword. This keyword indicates that the method belongs to the class.Example: Rotating a wheel or opening the hood in a car blueprint. These actions can be performed without needing a specific car instance.
Non-Static Methods:
Behaviors accessible only through an object (instance) of the class. They operate on the specific state of an object.
Do not have the
statickeyword. This absence indicates that the method requires an object instance to be called.Example: Turning on the engine or driving requires creating a car from the blueprint. These actions are specific to a particular car.
Class Variables
Also known as static fields. These variables are associated with the class itself.
States that belong to the class itself. They are shared among all instances of the class.
Changes to class variables affect all instances of the class. Modifying a class variable changes the value for all objects of that class.
Example: Changing the wheel size or vehicle type. If the wheel size is changed, all car instances will reflect this change.
Instance Variables
Also known as non-static fields. These variables hold the state of a specific object.
Variables that can't be accessed until an class is instantiated. They are unique to each instance.
Values are specific to each object instance. Each object has its own copy of instance variables.
Changes to instance variables in one object do not affect other objects. Modifying an instance variable only affects the object on which it was changed.
Example: Color and license plate. Each car can have a different color and license plate.
Additional Notes
Static methods can only access class variables. They cannot directly access instance variables because they don't operate on a specific instance.
Non-static methods can access both class variables and instance variables. They can operate on the state of a specific object and the shared state of the class.
The
privatekeyword restricts direct access to fields from other classes. This enforces encapsulation and protects the internal state of the object.
Sample Class Code
class AudieA8 {
private static int wheelSize; // Class variable
private String color; // Instance variable
private static void rotateWheel() { // Static method }
public void turnOnEngine() { // Non-static method }
// Getter and setter methods (not shown)
}
Using the Sample Class
public class Main {
public static void main(String[] args) {
AudieA8.rotateWheel(); // Calling static method from the class
AudieA8 janesCar = new AudieA8(); // Creating an instance
janesCar.rotateWheel(); // Calling static method from an instance
janesCar.turnOnEngine(); // Calling non-static method from an instance
}
}
private static int wheelSize: Class variable (static). Belongs to the class and is shared among all instances.private String color: Instance variable (non-static). Unique to each instance of the class.Changes to
wheelSizeaffect all instances; changes tocoloraffect only the specific instance. This demonstrates the difference between class and instance variables.
Declaring Methods
Method Header: Contains access modifier, static/non-static declaration, return type, method name, and parameters. It provides essential information about the method.
Method Body: Code block enclosed in curly brackets
{}that defines the method's actions. This is where the actual logic of the method is implemented.
Method Header Components
Access Modifier:
public(accessible from anywhere) orprivate(accessible only within the class). Determines the visibility and accessibility of the method.Static or Non-Static: Determines which fields the method can access and how it can be called. Static methods operate on the class, while non-static methods operate on instances.
Return Type: Specifies the type of data the method returns (
voidfor no return). Indicates the type of value the method will produce after execution.Method Name: Descriptive and in lower camel case. Should clearly indicate the purpose of the method.
Parameters: Data passed to the method, defined within parentheses. Multiple parameters are comma-separated. Allows the method to accept input for processing.
Indentation Styles
Allman style: Opening curly bracket on the next line. This is a matter of coding style preference.
K&R style: Opening curly bracket on the same line as the declaration. Another common coding style.
Getter and Setter Methods
Also known as accessor and mutator methods. These methods are used to access and modify the values of private fields in a class.
Purpose
Provide controlled access to private fields. Encapsulation is achieved by controlling how the internal state of an object is accessed and modified.
Getter methods: Return the value of a field. Allow you to retrieve the value of a private field.
Setter methods: Set (modify) the value of a field. Allow you to change the value of a private field, often with validation or additional logic.
Example: Student Class
class Student {
private int studentID; // Instance variable
private static String mascot; // Class variable
public int getStudentID() {
return studentID;
}
public void setStudentID(int newStudentID) {
studentID = newStudentID;
}
public static String getMascot() {
return mascot;
}
public static void setMascot(String newMascot) {
mascot = newMascot;
}
}
Memory Representation
Instance variables are stored within each instance on the heap. Each object has its own memory space for instance variables.
Class variables have a single copy stored separately. There is only one copy of a class variable, shared among all instances, usually stored in a static memory area.
Static methods can be called from the class or an instance. However, they operate on the class itself, not a specific instance.
Changes to class variables affect all instances. Modifying a class variable changes the value for all objects of that class because they share the same variable.
Overloading Methods
Methods within the same class sharing the same name. This allows you to define multiple methods with the same name but different parameters.
Requirements
Must have the exact same name. The method names must be identical.
Must have different number and/or types of parameters. This is how Java distinguishes between overloaded methods.
Constructors can also be overloaded. You can have multiple constructors with different parameters to create objects in different ways.
Differences
Can't have different method names. Overloaded methods must have the same name.
Can have different return types. The return type is not part of the method signature used to distinguish overloaded methods.
Can have different visibility (public/private). The access modifier is not part of the method signature.
Can have different static or non-static values. Whether a method is static or non-static does not affect overloading.
Can have different parameter names. The names of the parameters do not matter for overloading; only the types and order of the parameters are considered.
Examples
Different Number of Parameters:
void outputAnswer() {} void outputAnswer(int x) {} void outputAnswer(int x, int y) {}Different Types of Parameters:
void calculateAnswer(int x) {} void calculateAnswer(double x) {} void calculateAnswer(String x) {}Different Order of Parameter Types:
void computeAnswer(int x, double y) {} void computeAnswer(double x, int y) {}
Constructors
Special non-static method that runs when an object is first created. Used to initialize the object's state.
Used for setting up the new object. It performs any necessary setup operations when an object is created.
Has the same name as the class. This is how Java identifies a constructor.
Can be overloaded (multiple constructors with different parameters). Allows you to create objects in different ways with different initial states.
If no constructor is defined, Java provides a default no-parameter constructor. This default constructor initializes the object with default values for its fields.
Example
class Robot {
static String fuelSource; // Class variable
String name; // Instance variable
public Robot() {
fuelSource = "electricity";
name = generateRandomName();
}
private String generateRandomName() {
int rand = (int) (Math.random() * 3) + 1;
if (rand == 1) return "Bender";
if (rand == 2) return "HAL 9000";
return "GORT";
}
}
Using this in Constructors
this()can call another constructor within the same class. This is useful for reducing code duplication.Must be the first line in the constructor. It must be the first statement in the constructor body.
Overloading Constructors
Java differentiates between constructors based on their parameters. The parameters determine which constructor is called.
If the parameters are ambiguous, this can result in an error because the compiler won't know which constructor to call. The compiler needs to be able to uniquely identify the constructor based on the provided arguments.
The this Keyword
Contains a pointer to whatever object it is currently in. It refers to the current object instance.
Does not need to be declared. It is implicitly available in non-static methods and constructors.
Can only be used in non-static methods or constructors. It is not available in static methods because they do not operate on a specific object instance.
Uses
Specify a field over another variable of the same name. When a local variable has the same name as a field,
thisis used to refer to the field.Call another constructor in the same class.
this()is used to invoke another constructor in the same class.Pass a copy of a pointer reference back to the current class. This can be useful for certain design patterns or when passing the current object to another method.
Examples
class Example {
private static int x; // Static field
private int y; // Non-static field
public void printX(int x) {
System.out.println(x); // Accessing local variable
System.out.println(Example.x); //Accessing static field, this not necessary
}
public void setY(int y) {
this.y = y; // Using 'this' to refer to the field
}
Scope and Lifetime of Variables
Scope: Determines where a variable can be accessed. It defines the region of the code where the variable is visible and can be used.
Lifetime: Determines when a variable is created and destroyed. It specifies the duration for which the variable exists in memory.
Determined by where the variable is declared. The location of the variable declaration determines its scope and lifetime.
Local variables: Declared inside a method. Their scope is limited to the method in which they are declared.
Class variables: Declared with the
statickeyword. They have class-level scope and exist for the lifetime of the class.Instance variables: Declared without the
statickeyword. They have object-level scope and exist for the lifetime of the object.
Examples
public class ScopeExample {
public static void main(String[] args) {
int a; // Scope: entire main method
a = 3; //Lifetime: entire main method.
{
int b = 5; // Scope: inside this block
} //Lifetime: Ends here.
for (int c = 0; c < 10; c++) {
int d; //Scope: inside the for loop; d's Created and destroyed every cycle.
} // Lifetime for c ends here.
}
}
Parameters have scope within the method. They are only accessible within the method's body.
Lifetime begins when the method is called and ends when the method returns. Parameters are created when the method is invoked and destroyed when the method completes.
Class variables:
Created when the class is first used. They are initialized when the class is loaded into memory.
Accessible in all static and non-static methods. They can be accessed from any method within the class.
Shared across all instances. All objects of the class share the same class variables.