Getting Started
As programs become more complex, we need ways to model real-world entities like bank accounts, students, or cars. Primitive data types like int and double are not enough to capture both the data (attributes) and the behaviors of such concepts. Object-Oriented Programming (OOP) solves this by allowing us to design our own custom data types, creating logical and reusable components that make our code easier to build and understand.
What You Should Be Able to Do
Explain the relationship between a class (a blueprint) and an object (an instance).
Define a simple class containing attributes (instance variables) and behaviors (methods).
Write a constructor to initialize the state of a new object upon creation.
Create objects (instances) of a class using the
newkeyword.Explain how abstraction simplifies program design by hiding implementation complexity.
Key Concepts & Java Implementation
The Core Idea
The central concept in this topic is abstraction. Abstraction is the process of hiding complex implementation details and showing only the essential features of an object. Think about driving a car: you use a steering wheel, accelerator, and brake. You don't need to know the details of the engine's combustion cycle or the hydraulic brake system to operate the car. The car's controls provide a simple interface to its complex internal workings.
In Java, we achieve abstraction by creating classes. A class is a blueprint or template for creating objects. It defines a new data type by bundling together:
Attributes (Data): The characteristics of the entity, stored in instance variables. For a
Studentclass, this might be a name and GPA.Behaviors (Functionality): The actions the entity can perform, defined in methods. A
Studentmight have a method to print its information.
An object is a specific, concrete instance of a class. If Student is the blueprint, then individual students like "Maria," "David," and "Chen" are the objects created from that blueprint. Each object has its own set of instance variables.
Syntax & Implementation
To design a class, we define its variables and methods. To use that class, we write "client code" that creates and interacts with objects of that class.
Syntax Table
| Keyword/Concept | Purpose | Java Example |
|---|---|---|
class | A keyword used to declare a new class (a blueprint for objects). | public class Car { ... } |
private | An access modifier that restricts access to a variable or method to only within the declared class. | private String model; |
public | An access modifier that allows access to a class, constructor, or method from any other class. | public Car(String aModel) { ... } |
new | An operator that allocates memory for a new object and creates an instance of a class. | Car myCar = new Car("Sedan"); |
| Constructor | A special method that initializes a newly created object. It has the same name as the class. | public Car(String aModel) { model = aModel; } |
Annotated Java Example: The Class Blueprint
Here is the design for a Book class. This code would be saved in a file named Book.java. It defines the attributes and behaviors for any Book object.
// Defines the blueprint for all Book objects
public class Book {
// 1. Instance Variables: Attributes for each Book object
// They are 'private' to hide them from outside access (abstraction).
private String title;
private String author;
private int pageCount;
// 2. Constructor: A special method to initialize a new Book object
// It takes parameters to set the initial state of the instance variables.
public Book(String bookTitle, String bookAuthor, int numPages) {
title = bookTitle;
author = bookAuthor;
pageCount = numPages;
}
// 3. Method: A behavior for Book objects
// This 'public' method allows client code to get a summary of the book.
public String getSummary() {
return "Title: " + title + ", Author: " + author;
}
}
Annotated Java Example: Client Code (Creating and Using Objects)
This code would be in a different file (e.g., Library.java). It acts as a "client" of the Book class by creating and using Book objects.
public class Library {
public static void main(String[] args) {
// 1. Create an instance (object) of the Book class
// The 'new' keyword calls the Book constructor to create the object.
Book book1 = new Book("The Hobbit", "J.R.R. Tolkien", 310);
// 2. Create a second, distinct instance of the Book class
Book book2 = new Book("Dune", "Frank Herbert", 412);
// 3. Call a method on the first object
// The client code doesn't know HOW getSummary() works, only what it does.
String summary1 = book1.getSummary();
System.out.println(summary1); // Prints: Title: The Hobbit, Author: J.R.R. Tolkien
// 4. Call the same method on the second object
String summary2 = book2.getSummary();
System.out.println(summary2); // Prints: Title: Dune, Author: Frank Herbert
}
}
Tracing & Analysis
Execution Trace
Let's trace the line Book book1 = new Book("The Hobbit", "J.R.R. Tolkien", 310);.
new Book(...): Java allocates a new block of memory for aBookobject. This block contains space for its threeprivateinstance variables:title,author, andpageCount.Constructor Call: The
Bookconstructor is automatically called.The parameter
bookTitlereceives"The Hobbit".The parameter
bookAuthorreceives"J.R.R. Tolkien".The parameter
numPagesreceives310.
Initialization: Inside the constructor, the instance variables for this specific object are assigned their initial values:
titlebecomes"The Hobbit".authorbecomes"J.R.R. Tolkien".pageCountbecomes310.
Book book1 = ...: The memory address of the newly created and initialized object is assigned to the reference variablebook1. Now,book1refers to this specificBookobject.
Analysis
The power of abstraction is that the Library class (the client) does not need to know that the Book class has variables named title or author. The client simply calls the publicgetSummary() method. If the author of the Book class later decided to rename the title variable to bookTitle, the Library class would not need to be changed at all, as long as the getSummary() method still works as expected. This separation of interface (what it does) from implementation (how it does it) is key to managing large programs.
Java Syntax Quick-Reference
public class ClassName { ... }: Declares a new class namedClassNamethat is accessible to other classes.private dataType variableName;: Declares aprivateinstance variable, accessible only within the class.public ClassName(parameters) { ... }: Declares apublicconstructor used to initialize a new object. It must have the same name as the class and no return type.new ClassName(arguments): Creates a new instance ofClassNameby allocating memory and calling the matching constructor.objectReference.methodName(arguments): Calls a method on a specific object.
Core Code Examples & Terminology
Abstraction: The practice of hiding implementation details and exposing only necessary functionality. It simplifies complex systems by focusing on what an object does rather than how it does it.
Class: A template or blueprint for creating objects. It defines the common properties (instance variables) and behaviors (methods) that objects of that type will have.
Object (Instance): A specific instance of a class, created in memory. Each object has its own set of instance variables.
Constructor: A special method that is called when an object is created with the
newkeyword. Its purpose is to initialize the object's instance variables.Instance Variable: A variable declared inside a class but outside any method. Each object (instance) gets its own copy of these variables.
Method: A block of code within a class that defines a behavior or action that an object can perform.
Core Snippet 1 (Class Definition): A minimal class structure defining data and behavior.
public class Student { private String name; // Constructor and methods would go here... }Core Snippet 2 (Object Instantiation): Creating a new object from a class and assigning it to a reference variable.
// Assumes a Student(String) constructor exists Student student1 = new Student("Ananya");
Core Skill Check
Code Tracing: What is the output of this Java code?
// Given the Book class from the example above... Book myBook = new Book("Frankenstein", "Mary Shelley", 280); System.out.println(myBook.getSummary());Answer:
Title: Frankenstein, Author: Mary ShelleyDebugging: Identify the compile-time error in this client code.
// Given the Book class from the example above... Book b = new Book("1984", "George Orwell", 328); System.out.println(b.title); // <-- ERROR HEREError:
titlehas private access inBook. Client code cannot directly accessprivateinstance variables.Application: Write a single line of Java to create a
Carobject namedmyCarfor a 2023 Toyota, given the constructor:public Car(String make, int year).Answer:
Car myCar = new Car("Toyota", 2023);
Common Misconceptions & Errors
Confusing Class and Object: You cannot call a non-static method on a class name (e.g.,
Book.getSummary()). You must first create an object (Book b = new Book(...)) and then call the method on that object (b.getSummary()).Forgetting the
newKeyword: WritingBook b = Book("Title", "Author", 100);is a syntax error. You must usenewto create an object:Book b = new Book(...).Constructor has a Return Type: If you write
public void Book(...), you have accidentally created a regular method namedBook, not a constructor. Constructors must not have a return type, not evenvoid.No-Argument Constructor: If you define any constructor (e.g.,
public Book(String title)), Java no longer provides a default, no-argument constructor. Trying to callnew Book()will cause a compile-time error unless you explicitly define apublic Book() { ... }constructor yourself.
Summary
Classes and objects are the foundation of Object-Oriented Programming in Java. A class serves as a blueprint, defining the attributes (instance variables) and behaviors (methods) for a new data type. An object is a concrete instance created from that class blueprint. This model allows us to practice abstraction—hiding complex internal details from the user (or "client code") and providing a simple public interface. By using constructors to initialize objects and methods to interact with them, we can build robust, modular, and maintainable software that models the real world effectively.