L2: Why Object-Oriented Programming (OOP) in Java
Overview
Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around objects, which can represent real-world entities. Java uses OOP to make code more modular, reusable, and easier to maintain.
Key Concepts of OOP in Java
Classes and Objects:
A class is a blueprint for creating objects. It defines the attributes (variables) and behaviors (methods) that the objects created from the class will have.
An object is an instance of a class. Each object has its own set of attributes and can perform actions defined by its methods.
Example:
public class Car { // Attributes String color; int speed; // Constructor public Car(String color, int speed) { this.color = color; this.speed = speed; } // Method public void accelerate() { speed += 10; } } public class Main { public static void main(String[] args) { // Creating an object Car myCar = new Car("Red", 0); myCar.accelerate(); } }
Why OOP?
- OOP allows breaking down complex problems into smaller, manageable pieces.
- It improves code reusability by using classes as templates.
- Makes it easier to maintain and modify code since each part (class) can be updated independently.
Identifiers in Java
- Identifiers are names used for classes, methods, variables, etc. They must follow certain rules:
- Can contain letters, digits, underscores (_), and dollar signs ($).
- Cannot start with a digit or use reserved keywords (e.g.,
int
,class
). - They are case sensitive.
Declaring and Using Variables
Variables: Hold data that can be used and manipulated within the program. Java is statically-typed, which means you must declare the type of a variable when creating it:
int age = 25; String name = "Alice";
- The type of the variable must match the type of value assigned to it.
Assignment: The
=
operator is used to assign values to variables.Literals: A literal in Java is a fixed, specific value directly represented in the source code. It is a constant value that you assign to a variable or use in expressions. Since literals are not variables, their values are explicitly written and not meant to change during program execution.
Designing a Class with Attributes and Behaviors
A class defines attributes using variables and behaviors using methods. Each object created from the class will have its own copy of the attributes:
public class Dog { String breed; int age; public void bark() { System.out.println("Woof!"); } }
Creating and manipulating objects from a class:
Dog myDog = new Dog(); myDog.bark();
Benefits of OOP in Java
- Encapsulation: Bundles data (attributes) and code (methods) into a single unit (class).
- Modularity: Breaks down code into reusable parts, making it easier to update and maintain.
- Code Reusability: Classes can be used as templates for creating multiple objects with similar structures.