Understanding Object-Oriented Programming in Java
Object-Oriented Concepts
Object-oriented programming (OOP) organizes software design around objects rather than actions. In Java, this approach models real-world entities with properties (attributes) and behaviors (methods).
Key Differences from Procedural Programming
- Procedural: Focuses on step-by-step execution
- Object-oriented: Emphasizes objects and their interactions
Example: Washing clothes
- Procedural: Detailed manual steps
- OOP: Using a washing machine object
Core OOP Features
- Encapsulation
- Inheritance
- Polymorphism
Classes and Objects
A class defines a blueprint for objects, specifying their attributes and methods. An object is a specific instance of a class.
Example class definition:
public class Animal {
// Attributes
String name;
int age;
// Behaviors
public void eat() {
System.out.println("Eating...");
}
public void sleep() {
System.out.println("Sleeping...");
}
}
Creating and Using Objects
public class Main {
public static void main(String[] args) {
Animal cat = new Animal();
cat.name = "Whiskers";
cat.age = 3;
cat.eat();
cat.sleep();
}
}
Memory Management
- Objects reside in heap memory
- References to objects live in stack memory
- Methods are stored once in class definition
Encapsulation
Encapsulation protects data by restricting direct access to class members. Use private variables with public getter/setter methods.
Example:
public class BankAccount {
private double balance;
public void setBalance(double amount) {
if (amount > 0) {
this.balance = amount;
}
}
public double getBalance() {
return balance;
}
}
Constructors
Constructors initialize new objects. Java provides a default no-arg constructor if none is defined.
public class Book {
private String title;
private String author;
// Default constructor
public Book() {}
// Parameterized constructor
public Book(String title, String author) {
this.title = title;
this.author = author;
}
}
JavaBean Standard
A proper JavaBean includes:
- Private feilds
- Public no-arg constructor
- Getter/setter methods
- Serializable implmeentation (optional)
Example:
public class Employee implements Serializable {
private String id;
private String department;
public Employee() {}
public Employee(String id, String dept) {
this.id = id;
this.department = dept;
}
// Getters and setters
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
// Additional methods...
}