0% found this document useful (0 votes)
3 views28 pages

Chapter 8 - Classes - Study Guide

Chapter 8 introduces object-oriented programming concepts in Java, focusing on classes that define new object types combining state and behavior. It covers key definitions such as objects, state, behavior, and different class types (executable, module, and instantiable), along with constructors and methods. The chapter emphasizes encapsulation, the use of 'this' keyword, and static members to manage shared data and functionality.

Uploaded by

Mahad Dahir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views28 pages

Chapter 8 - Classes - Study Guide

Chapter 8 introduces object-oriented programming concepts in Java, focusing on classes that define new object types combining state and behavior. It covers key definitions such as objects, state, behavior, and different class types (executable, module, and instantiable), along with constructors and methods. The chapter emphasizes encapsulation, the use of 'this' keyword, and static members to manage shared data and functionality.

Uploaded by

Mahad Dahir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Chapter 8: Classes - Study Guide with Definitions and Examples

Overview
This chapter introduces object-oriented programming (OOP) concepts in Java, focusing on creating
and using classes to define new types of objects that combine state (data) and behavior (methods).
Key Concepts and Definitions
1. Object-Oriented Programming Fundamentals
Object: An entity that combines state and behavior
Definition: A specific instance of a class that contains its own data and can perform actions
Example: If you have a Point class, then Point p1 = new Point(5, 3); creates an object
p1 with coordinates (5, 3)

State: The data/information an object stores (represented by fields)


Definition: The current values of an object's variables at any given time
Example: A Point object's state includes its x and y coordinates
Behavior: The actions an object can perform (represented by methods)
Definition: The operations or functions that can be performed on or by an object
Example: A Point object can translate() (move), calculate distance() to another point, or
toString() (display itself)

Class: A blueprint or template for creating objects


Definition: A template that defines what data objects will store and what methods they will have
Example:
java

public class Point {


private int myX; // data that objects will store
private int myY;

public void translate(int theDx, int theDy) { // behavior objects will have
myX += theDx;
myY += theDy;
}
}

Client Program: A program that uses objects from a class


Definition: Any program that creates and uses objects of a particular class
Example:
java

public class PointMain { // This is a client of the Point class


public static void main(String[] args) {
Point p1 = new Point(5, 3); // Using Point class
p1.translate(2, 1); // Using Point's behavior
}
}

Abstraction: A distancing between ideas and details


Definition: The ability to use objects without knowing how they work internally
Example: You can use System.out.println() without knowing how printing actually works
2. Three Types of Classes
1. Executable Class
Definition: A class that contains a main method and can be run as a program
Characteristics: All methods are static, may have constants
Example:
java

public class HelloWorld { // Executable class


public static void main(String[] args) { // Entry point
System.out.println("Hello, World!");
}

public static void sayGoodbye() { // Static method


System.out.println("Goodbye!");
}
}

2. Module Class
Definition: A class containing utility methods that don't require object creation
Characteristics: All methods are static, used by other classes
Example:
java

public class MathUtils { // Module class


public static int square(int theNumber) {
return theNumber * theNumber;
}

public static boolean isEven(int theNumber) {


return theNumber % 2 == 0;
}
}

// Usage: int result = MathUtils.square(5);

3. Instantiable Class (Object Class)


Definition: A class that defines a new type of object that must be instantiated to use
Characteristics: Has instance fields, constructors, and non-static methods
Example:
java

public class BankAccount { // Instantiable class


private double myBalance; // Instance field

public BankAccount(double theInitialBalance) { // Constructor


myBalance = theInitialBalance;
}

public void deposit(double theAmount) { // Instance method


myBalance += theAmount;
}
}

// Usage: BankAccount account = new BankAccount(100.0);

Fields (Instance Variables)


Definition and Examples
Field: A variable inside an object that is part of its state
Definition: Instance variables that store data for each individual object
Key Point: Each object has its own copy of each field
Syntax:
java

private type myFieldName;

Example:
java

public class Student {


private String myName; // Each Student object has its own name
private double myGpa; // Each Student object has its own GPA
private int myAge; // Each Student object has its own age
}

Field Access Examples:


java

// If fields were public (NOT recommended):


Point p1 = new Point();
p1.myX = 7; // Setting field value
System.out.println(p1.myX); // Getting field value

// With multiple objects:


Point p2 = new Point();
p2.myX = 10; // p2's myX is different from p1's myX

Parallel Arrays Problem (Why we need objects):


java

// BAD: Using parallel arrays


int[] xCoords = {50, 90, 10};
int[] yCoords = {20, 60, 72};

// GOOD: Using objects


Point[] cities = {
new Point(50, 20),
new Point(90, 60),
new Point(10, 72)
};

Constructors
Definition and Examples
Constructor: A special method that initializes the state of new objects
Definition: Code that runs when creating a new object with the new keyword
Key Points: No return type, same name as class, can have parameters
Basic Constructor Syntax:
java

public ClassName(parameters) {
// initialization statements
}

Constructor Examples:
java

public class Point {


private int myX;
private int myY;

// Constructor with parameters


public Point(int theInitialX, int theInitialY) {
myX = theInitialX;
myY = theInitialY;
}

// Default constructor (no parameters)


public Point() {
myX = 0;
myY = 0;
}
}

// Usage examples:
Point p1 = new Point(5, 3); // Uses first constructor
Point p2 = new Point(); // Uses default constructor

Constructor Tracing Example:


java

Point p1 = new Point(7, 2);


// Step 1: new Point object created in memory
// Step 2: Constructor called with theInitialX=7, theInitialY=2
// Step 3: myX = 7, myY = 2
// Step 4: Reference to object stored in p1

Multiple Constructors Example:


java

public class BankAccount {


private double myBalance;
private String myOwner;

// Constructor with balance and owner


public BankAccount(double theBalance, String theOwner) {
myBalance = theBalance;
myOwner = theOwner;
}

// Constructor with just owner (starts with $0)


public BankAccount(String theOwner) {
myBalance = 0.0;
myOwner = theOwner;
}

// Constructor calling another constructor


public BankAccount() {
this("Unknown Owner"); // Calls the constructor above
}
}

Common Constructor Mistakes:


java

// WRONG: Shadowing (redeclaring fields)


public Point(int theX, int theY) {
int myX = theX; // Creates local variable, doesn't set field!
int myY = theY; // Field remains 0
}

// WRONG: Adding return type


public void Point(int theX, int theY) { // This is a method, not constructor!
myX = theX;
myY = theY;
}

// CORRECT:
public Point(int theX, int theY) {
myX = theX;
myY = theY;
}

Methods
Instance Methods
Instance Method: A method that exists inside each object and operates on that object's data
Definition: Methods that belong to objects and can access the object's fields directly
Key Point: Each object has its own copy of the method that works with that object's data
Syntax:
java

public returnType methodName(parameters) {


statements;
}

The Implicit Parameter: The object on which an instance method is called


Definition: When you call object.method() , the object becomes the implicit parameter
Example:
java

Point p1 = new Point(5, 2);


Point p2 = new Point(3, 4);

p1.translate(1, 1); // p1 is the implicit parameter


p2.translate(2, 2); // p2 is the implicit parameter

Method Types with Examples


1. Accessor Methods (Getters)
Definition: Methods that let clients examine object state without changing it
Examples:
java

public class Point {


private int myX;
private int myY;

// Simple accessor - returns field value


public int getX() {
return myX;
}

public int getY() {


return myY;
}

// Calculated accessor - returns computed value


public double distanceFromOrigin() {
return Math.sqrt(myX * myX + myY * myY);
}

// Accessor with parameter


public double distance(Point theOther) {
int dx = myX - theOther.myX;
int dy = myY - theOther.myY;
return Math.sqrt(dx * dx + dy * dy);
}
}

// Usage:
Point p = new Point(3, 4);
System.out.println("X coordinate: " + p.getX()); // 3
System.out.println("Distance from origin: " + p.distanceFromOrigin()); // 5.0

2. Mutator Methods (Setters)


Definition: Methods that modify an object's state
Examples:
java

public class Point {


private int myX;
private int myY;

// Simple mutator - sets field value


public void setX(int theNewX) {
myX = theNewX;
}

// Mutator with multiple parameters


public void setLocation(int theNewX, int theNewY) {
myX = theNewX;
myY = theNewY;
}

// Mutator that modifies existing values


public void translate(int theDx, int theDy) {
myX += theDx;
myY += theDy;
}

// Alternative implementation using another method


public void translate2(int theDx, int theDy) {
setLocation(myX + theDx, myY + theDy);
}
}

// Usage:
Point p = new Point(5, 3);
p.setX(10); // Changes x to 10
p.translate(2, 1); // Moves point by (2, 1)
p.setLocation(0, 0); // Moves point to origin

The toString() Method


Definition and Examples
toString() Method: A special method that tells Java how to convert an object into a String
Definition: Automatically called when an object is printed or concatenated with a String
Key Point: Must have exact signature: public String toString()
Without toString():
java

Point p = new Point(10, 7);


System.out.println("Point: " + p); // Output: Point: Point@9e8c34

With toString():
java

public class Point {


private int myX;
private int myY;

public String toString() {


return "(" + myX + ", " + myY + ")";
}
}

// Usage:
Point p = new Point(10, 7);
System.out.println("Point: " + p); // Output: Point: (10, 7)
System.out.println(p.toString()); // Output: (10, 7)

More Complex toString() Examples:


java

public class Student {


private String myName;
private double myGpa;
private int myAge;

public String toString() {


return myName + " (age " + myAge + ", GPA: " + myGpa + ")";
}
}

// Usage:
Student s = new Student("Alice", 3.8, 20);
System.out.println(s); // Output: Alice (age 20, GPA: 3.8)
Encapsulation
Definition and Examples
Encapsulation: Hiding implementation details from clients
Definition: Making fields private and providing controlled access through methods
Purpose: Protects object data and allows internal changes without affecting clients
Private Fields:
java

public class BankAccount {


private double myBalance; // Cannot be accessed directly from outside
private String myOwner;

// Controlled access through methods


public double getBalance() {
return myBalance;
}

public void deposit(double theAmount) {


if (theAmount > 0) { // Validation
myBalance += theAmount;
}
}

public boolean withdraw(double theAmount) {


if (theAmount > 0 && theAmount <= myBalance) {
myBalance -= theAmount;
return true;
}
return false; // Insufficient funds
}
}

Benefits Example:
java

// Without encapsulation (BAD):


BankAccount account = new BankAccount();
account.myBalance = -1000; // Fraudulent negative balance!

// With encapsulation (GOOD):


BankAccount account = new BankAccount();
account.deposit(100); // Controlled access
account.withdraw(50); // Validated operation
// account.myBalance = -1000; // Compilation error - cannot access private field

Accessor/Mutator Pattern Example:


java

public class Person {


private String myName;
private int myAge;

// Accessors (getters)
public String getName() {
return myName;
}

public int getAge() {


return myAge;
}

// Mutators (setters) with validation


public void setName(String theName) {
if (theName != null && theName.length() > 0) {
myName = theName;
}
}

public void setAge(int theAge) {


if (theAge >= 0 && theAge <= 150) { // Reasonable age range
myAge = theAge;
}
}
}
The this Keyword
Definition and Examples
this Keyword: Refers to the current object (the implicit parameter)
Definition: A reference to the object on which a method is currently being executed
Uses: Resolve naming conflicts, call other methods, call other constructors
Resolving Naming Conflicts:
java

public class Point {


private int myX;
private int myY;

// Without naming conflicts (preferred approach)


public void setLocation(int theX, int theY) {
myX = theX;
myY = theY;
}

// With naming conflicts - need 'this'


public void setLocation2(int x, int y) {
this.myX = x; // this.myX refers to the field
this.myY = y; // x and y refer to parameters
}
}

Calling Other Methods:


java

public class Point {


private int myX;
private int myY;

public void setLocation(int theX, int theY) {


myX = theX;
myY = theY;
}

public void translate(int theDx, int theDy) {


this.setLocation(myX + theDx, myY + theDy); // Calling another method
// or simply: setLocation(myX + theDx, myY + theDy);
}
}

Constructor Chaining:
java

public class Point {


private int myX;
private int myY;

public Point(int theX, int theY) {


myX = theX;
myY = theY;
}

public Point() {
this(0, 0); // Calls the other constructor
}

public Point(int theCoordinate) {


this(theCoordinate, theCoordinate); // Creates point at (n, n)
}
}

Static Members
Static Fields
Static Field: A field that belongs to the class rather than to individual objects
Definition: Shared by all objects of the class; only one copy exists
Use Case: Data that should be shared across all instances
Example:
java

public class Student {


private static int ourStudentCount = 0; // Shared by all students
private String myName;
private int myId;

public Student(String theName) {


ourStudentCount++; // Increment shared counter
myName = theName;
myId = ourStudentCount; // Each student gets unique ID
}

public static int getStudentCount() {


return ourStudentCount;
}

public int getId() {


return myId;
}
}

// Usage:
Student s1 = new Student("Alice"); // ourStudentCount becomes 1
Student s2 = new Student("Bob"); // ourStudentCount becomes 2
System.out.println(Student.getStudentCount()); // Output: 2
System.out.println(s1.getId()); // Output: 1
System.out.println(s2.getId()); // Output: 2

Static Methods
Static Method: A method that belongs to the class rather than to individual objects
Definition: Cannot access instance fields or methods directly; no implicit parameter
Use Case: Utility methods that don't need object data
Example:
java

public class MathHelper {


// Static method - belongs to class
public static int max(int theA, int theB) {
if (theA > theB) {
return theA;
} else {
return theB;
}
}

// Static method using static field


private static final double PI = 3.14159;

public static double circleArea(double theRadius) {


return PI * theRadius * theRadius;
}
}

// Usage - called on class, not objects:


int bigger = MathHelper.max(5, 8); // Returns 8
double area = MathHelper.circleArea(3.0); // Returns ~28.27

Static vs Instance Methods Example:


java

public class BankAccount {


private static int ourAccountCount = 0; // Static field
private double myBalance; // Instance field

public BankAccount(double theBalance) {


myBalance = theBalance;
ourAccountCount++;
}

// Static method - can access static fields only


public static int getTotalAccounts() {
return ourAccountCount;
// return myBalance; // ERROR: cannot access instance field
}

// Instance method - can access both static and instance fields


public void displayInfo() {
System.out.println("Balance: " + myBalance); // Instance field
System.out.println("Total accounts: " + ourAccountCount); // Static field
}
}

Null and Object Arrays


Definition and Examples
null: A value that does not refer to any object
Definition: A special value indicating "no object"
Key Point: Array elements are initialized to null
Null Examples:
java

// Creating array of objects


Point[] points = new Point[3]; // All elements are null initially

// Checking for null


if (points[0] == null) {
System.out.println("No point created yet");
}

// Creating objects
points[0] = new Point(1, 2);
points[1] = new Point(3, 4);
// points[2] is still null

// Safe access
for (int i = 0; i < points.length; i++) {
if (points[i] != null) {
System.out.println(points[i].toString());
}
}

Null Pointer Exception Example:


java

String[] words = new String[5];


System.out.println(words[0]); // Prints: null
System.out.println(words[0].length()); // ERROR: NullPointerException!

// Safe approach:
if (words[0] != null) {
System.out.println(words[0].length());
}

Two-Phase Initialization:
java

// Phase 1: Create array (elements are null)


Student[] students = new Student[3];

// Phase 2: Create objects for each element


students[0] = new Student("Alice");
students[1] = new Student("Bob");
students[2] = new Student("Charlie");

// Now safe to use:


for (Student s : students) {
System.out.println(s.toString());
}

Complete Class Examples


Example 1: Point Class (Full Implementation)
java
public class Point {
private int myX;
private int myY;

// Constructors
public Point(int theX, int theY) {
myX = theX;
myY = theY;
}

public Point() {
this(0, 0); // Default to origin
}

// Accessors
public int getX() {
return myX;
}

public int getY() {


return myY;
}

public double distance(Point theOther) {


int dx = myX - theOther.myX;
int dy = myY - theOther.myY;
return Math.sqrt(dx * dx + dy * dy);
}

public double distanceFromOrigin() {


return distance(new Point(0, 0));
}

// Mutators
public void setLocation(int theX, int theY) {
myX = theX;
myY = theY;
}

public void translate(int theDx, int theDy) {


myX += theDx;
myY += theDy;
}
// toString
public String toString() {
return "(" + myX + ", " + myY + ")";
}
}

Example 2: BankAccount Class with Static Counter


java
public class BankAccount {
// Static field - shared by all accounts
private static int ourNextAccountNumber = 1000;

// Instance fields - each account has its own


private double myBalance;
private String myOwner;
private int myAccountNumber;

// Constructor
public BankAccount(String theOwner, double theInitialBalance) {
myOwner = theOwner;
myBalance = theInitialBalance;
myAccountNumber = ourNextAccountNumber;
ourNextAccountNumber++;
}

// Accessors
public double getBalance() {
return myBalance;
}

public String getOwner() {


return myOwner;
}

public int getAccountNumber() {


return myAccountNumber;
}

// Static method
public static int getNextAccountNumber() {
return ourNextAccountNumber;
}

// Mutators
public void deposit(double theAmount) {
if (theAmount > 0) {
myBalance += theAmount;
}
}

public boolean withdraw(double theAmount) {


if (theAmount > 0 && theAmount <= myBalance) {
myBalance -= theAmount;
return true;
}
return false;
}

// toString
public String toString() {
return "Account #" + myAccountNumber + " (" + myOwner + "): $" + myBalance;
}
}

// Usage example:
BankAccount account1 = new BankAccount("Alice", 500.0); // Account #1000
BankAccount account2 = new BankAccount("Bob", 300.0); // Account #1001
System.out.println(account1); // Account #1000 (Alice): $500.0
account1.deposit(100);
account1.withdraw(50);
System.out.println(account1); // Account #1000 (Alice): $550.0

Study Tips and Practice


Key Concepts to Master
1. Class vs Object: Understand that a class is a blueprint, objects are instances
2. Constructor Purpose: Know that constructors initialize object state
3. Method Types: Distinguish between accessors (examine state) and mutators (change state)
4. Encapsulation: Always make fields private, provide controlled access through methods
5. Static vs Instance: Understand what belongs to the class vs what belongs to objects
6. this Keyword: Know when and how to use it for clarity
7. toString(): Remember the exact signature and purpose
Common Mistakes to Avoid
1. Making fields public instead of private
2. Forgetting to initialize fields in constructors
3. Using static methods when you need instance methods
4. Not checking for null before using objects
5. Shadowing fields with local variables in constructors
6. Adding return types to constructors
Practice Exercises
Try implementing these classes with proper encapsulation:
Rectangle: fields for width/height, methods for area/perimeter
Car: fields for make/model/year, methods for displaying info
Circle: fields for radius, methods for area/circumference
Student: fields for name/grades, methods for GPA calculation
This comprehensive guide provides definitions and detailed examples for all major concepts in Chapter
8, helping you understand both the theory and practical application of object-oriented programming in
Java.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy