Home | Review | Approach and Practice | Homework |
FRQ Teaching | Classes | Home
Lesson for class FRQs
Intro/Review
What Are Classes in Java?
Definition: A class is a blueprint for creating objects. It encapsulates data (fields) and behaviors (methods).
- Why Are Classes Important?
- Organize code into reusable, modular units.
- Support Object-Oriented Programming (OOP) principles:
- Encapsulation: Keep data safe by hiding it.
- Abstraction: Simplify complex systems.
- Inheritance: Reuse code.
- Polymorphism: Make programs more flexible and scalable.
- Components of a Class
- Fields (Attributes): Variables that represent the state of the object.
- Methods: Functions that define the object’s behavior.
- Constructors: Special methods to initialize objects.
- Access Modifiers: Define how fields and methods can be accessed (private, public, protected).
- Levels of Access:
- private: Accessible only within the class.
- public: Accessible anywhere.
- protected: Accessible within the package and subclasses.
- Default (no modifier): Accessible within the package.
public class Book {
// Private Fields (encapsulation)
private String title;
private String author;
private int pages;
// Constructor
public Book(String title, String author, int pages) {
this.title = title;
this.author = author;
this.pages = pages;
}
// Accessor Methods (Getters)
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
// Mutator Methods (Setters)
public void setPages(int pages) {
if (pages > 0) {
this.pages = pages;
} else {
System.out.println("Invalid page count.");
}
}
// Method
public void displayInfo() {
System.out.println("Book: " + title + " by " + author + ", Pages: " + pages);
}
}
Object Oriented Programming Principles
- encapsulate: Keep fields private, provide controlled access using getters and setters (ex. book class)
- Inheritance: Allow a new class (subclass) to inherit from an existing class (superclass)
- Polymorphism: The ability to use the same method name in different contexts.
- Method Overloading: Same method name, different parameter lists.
- Method Overriding: Subclass provides a specific implementation of a method from the superclass.
During the Exam
- Constructors: initialize objects
- Static Variables
- Not always given, will need to identify on your own
- Methods:
- Names given, code is task. Methods team teach applies here
- Levels of Access:
- Will lose points, do not mess up