Unit 7: Object-Oriented Programming
Classes and Objects
- Definition: A class is a blueprint for creating objects. It defines attributes (fields) and methods (functions) that objects of the class will have.
- Example:
class Car { String make; String model; int year; void startEngine() { // Code to start the car's engine } }
Constructors
- Definition: Constructors are special methods used to initialize objects when they are created. They have the same name as the class and no return type.
- Example:
class Car { String make; String model; int year; Car(String make, String model, int year) { this.make = make; this.model = model; this.year = year; } }
Inheritance
- Definition: Inheritance allows a subclass to inherit attributes and methods from a superclass. It promotes code reuse and supports the “is-a” relationship.
- Example:
class Animal { String name; void eat() { // Code for eating } } class Dog extends Animal { void bark() { // Code for barking } }
Polymorphism
- Definition: Polymorphism allows objects of different classes to be treated as objects of a common superclass. It supports method overriding and dynamic binding.
- Example:
class Animal { void makeSound() { // Default animal sound } } class Dog extends Animal { @Override void makeSound() { // Dog's sound } }
Encapsulation
- Definition: Encapsulation restricts access to certain components of an object and hides the internal details. It uses private and public access modifiers.
- Example:
class Student { private int age; public int getAge() { return age; } public void setAge(int age) { if (age >= 0) { this.age = age; } } }
Abstraction
- Definition: Abstraction focuses on the essential features of an object while hiding unnecessary details. It uses abstract classes and methods.
- Example:
abstract class Shape { abstract double area(); } class Circle extends Shape { double radius; @Override double area() { return Math.PI * radius * radius; } }
Static Members
- Definition: Static members (variables and methods) belong to the class itself rather than instances of the class. They are accessed using the class name.
- Example:
class MathUtils { static final double PI = 3.14159265359; static int add(int a, int b) { return a + b; } }