Java Classes and Objects
Learn the foundation of Object-Oriented Programming - how to create and use classes and objects in Java
What is a Class?
A class is a blueprint or template for creating objects. It defines the properties (variables) and behaviors (methods) that objects created from the class will have.
Think of a class like a cookie cutter and objects like the actual cookies. The cookie cutter defines the shape, but each cookie is a separate item.
- Class: A template that describes what properties and behaviors an object will have
- Object: An actual instance created from the class with real values
- Properties: Variables that store data (also called fields or attributes)
- Methods: Functions that define behaviors or actions
Real-World Example: A "Car" class is a blueprint that defines properties like color, brand, and speed. Each actual car (object) created from this blueprint has its own specific values for these properties.
Creating Your First Class
Let's create a simple class and understand its structure.
Example: Creating a Student Class
// Define a class named Student
class Student {
// Properties (variables)
String name;
int age;
String course;
// Method (behavior)
void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Course: " + course);
}
}
This class definition doesn't produce output yet. We need to create objects to use it.
Explanation:
class Student- Declares a new class named StudentString name, int age, String course- Properties that every Student object will havevoid displayInfo()- A method that displays student information
What is an Object?
An object is an instance of a class. When you create an object, you're creating a real entity with actual data based on the class blueprint.
Objects are created using the new keyword followed by the class name.
Example: Creating and Using Objects
class Student {
String name;
int age;
String course;
void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Course: " + course);
System.out.println("-------------------");
}
}
public class Main {
public static void main(String[] args) {
// Creating first object
Student student1 = new Student();
student1.name = "Alice";
student1.age = 20;
student1.course = "Computer Science";
// Creating second object
Student student2 = new Student();
student2.name = "Bob";
student2.age = 22;
student2.course = "Mathematics";
// Using the objects
student1.displayInfo();
student2.displayInfo();
}
}
Name: Alice Age: 20 Course: Computer Science ------------------- Name: Bob Age: 22 Course: Mathematics -------------------
Explanation:
Student student1 = new Student();- Creates a new Student object named student1student1.name = "Alice";- Assigns values to the object's properties using dot notationstudent1.displayInfo();- Calls the method on the object to display its information- Each object (student1, student2) has its own separate set of values
What is a Constructor?
A constructor is a special method that is automatically called when an object is created. It's used to initialize the object's properties with values.
- Constructor has the same name as the class
- Constructor has no return type (not even void)
- Constructor is called automatically when using the
newkeyword
Example: Using a Constructor
class Student {
String name;
int age;
String course;
// Constructor
Student(String n, int a, String c) {
name = n;
age = a;
course = c;
System.out.println("New student created!");
}
void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Course: " + course);
System.out.println("-------------------");
}
}
public class Main {
public static void main(String[] args) {
// Creating objects with constructor
Student student1 = new Student("Charlie", 21, "Engineering");
Student student2 = new Student("Diana", 19, "Biology");
student1.displayInfo();
student2.displayInfo();
}
}
New student created! New student created! Name: Charlie Age: 21 Course: Engineering ------------------- Name: Diana Age: 19 Course: Biology -------------------
Explanation:
Student(String n, int a, String c)- Constructor with parameters- Values are passed during object creation, making initialization cleaner and easier
- The constructor runs automatically when
new Student(...)is called
Tip:
Using constructors is much cleaner than setting each property separately. Compare: new Student("Alice", 20, "CS") vs setting name, age, and course one by one!
Types of Constructors
1. Default Constructor
A constructor with no parameters. If you don't create any constructor, Java automatically provides a default constructor.
Example: Student() { }
2. Parameterized Constructor
A constructor that accepts parameters to initialize object properties with specific values.
Example: Student(String name, int age) { this.name = name; this.age = age; }
3. Constructor Overloading
Having multiple constructors with different parameters in the same class. This gives flexibility in object creation.
Example: You can have both Student() and Student(String name, int age) in the same class
Constructor Overloading Example
Let's create multiple constructors to give flexibility in how objects are created.
Example: Multiple Constructors
class Car {
String brand;
String model;
int year;
// Constructor 1: No parameters
Car() {
brand = "Unknown";
model = "Unknown";
year = 2024;
}
// Constructor 2: Two parameters
Car(String b, String m) {
brand = b;
model = m;
year = 2024;
}
// Constructor 3: All parameters
Car(String b, String m, int y) {
brand = b;
model = m;
year = y;
}
void displayInfo() {
System.out.println(year + " " + brand + " " + model);
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car();
Car car2 = new Car("Toyota", "Camry");
Car car3 = new Car("Honda", "Civic", 2023);
car1.displayInfo();
car2.displayInfo();
car3.displayInfo();
}
}
2024 Unknown Unknown 2024 Toyota Camry 2023 Honda Civic
Explanation:
- Three different constructors provide different ways to create Car objects
- Java automatically calls the appropriate constructor based on the arguments provided
- This flexibility makes the class easier to use in different situations
The 'this' Keyword
The this keyword refers to the current object. It's useful when parameter names are the same as property names.
Example: Using 'this' Keyword
class Book {
String title;
String author;
double price;
// Using 'this' to differentiate between parameters and properties
Book(String title, String author, double price) {
this.title = title; // this.title refers to the object's property
this.author = author; // author refers to the parameter
this.price = price;
}
void displayInfo() {
System.out.println("Title: " + this.title);
System.out.println("Author: " + this.author);
System.out.println("Price: $" + this.price);
System.out.println("-------------------");
}
}
public class Main {
public static void main(String[] args) {
Book book1 = new Book("Java Programming", "John Doe", 45.99);
Book book2 = new Book("Python Basics", "Jane Smith", 39.99);
book1.displayInfo();
book2.displayInfo();
}
}
Title: Java Programming Author: John Doe Price: $45.99 ------------------- Title: Python Basics Author: Jane Smith Price: $39.99 -------------------
Explanation:
this.titlerefers to the object's property (class variable)title(without this) refers to the constructor parameter- Using
thismakes code clearer and avoids naming conflicts
Remember:
Use this when parameter names match property names. It tells Java "use THIS object's property, not the parameter."
Methods with Return Values
Methods can return values to the caller. Specify the return type before the method name.
Example: Methods with Return Types
class Calculator {
int num1;
int num2;
Calculator(int n1, int n2) {
num1 = n1;
num2 = n2;
}
// Method that returns an integer
int add() {
return num1 + num2;
}
int subtract() {
return num1 - num2;
}
int multiply() {
return num1 * num2;
}
double divide() {
if (num2 != 0) {
return (double) num1 / num2;
}
return 0;
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator(20, 5);
System.out.println("Addition: " + calc.add());
System.out.println("Subtraction: " + calc.subtract());
System.out.println("Multiplication: " + calc.multiply());
System.out.println("Division: " + calc.divide());
}
}
Addition: 25 Subtraction: 15 Multiplication: 100 Division: 4.0
Explanation:
int add()- Returns an integer resultreturn num1 + num2;- Sends the result back to the caller- The returned value can be stored in a variable or used directly
Key Takeaways
- Class: Blueprint that defines structure (properties and methods)
- Object: Real instance of a class with actual values
- Constructor: Special method to initialize objects automatically
- this keyword: Refers to the current object
- Methods: Define behaviors and can return values
- Multiple objects: Can be created from one class, each with its own data
Practice Tip: Try creating a "Phone" class with properties like brand, model, and price. Add a constructor and methods like displaySpecs() and applyDiscount(). Create multiple phone objects to practice!