[Java] Object-Oriented Programming Basics

Date:     Updated:

Categories:

Tags:

📋 Here are the notes summarizing what I learned from the course!


Introduction

This document provides an overview of key object-oriented programming concepts in Java as outlined in the textbook Data Structures and Algorithms in Java by Goodrich, Tamassia, and Goldwasser.


Classes and Objects

Definition

Classes act as blueprints for creating objects which are instances of classes.

public class Car {
    String color; // Data member
    void drive() { // Method
        System.out.println("This car is driving.");
    }
}


Encapsulation

Definition

Encapsulating data (variables) and methods within classes to prevent direct access and modification of data.

public class Account {
    private double balance; // Private variable
    public void deposit(double amount) { // Public method
        if (amount > 0) {
            balance += amount;
        }
    }
}


Inheritance

Definition

Using existing class features to create new classes.

public class Vehicle {
    int speed;
}
public class Bike extends Vehicle { // Inherits from Vehicle
    int wheels = 2;
}


Polymorphism

Definition

Methods performing different functions based on the object operating upon them.

public class Animal {
    void sound() {
        System.out.println("This animal makes a sound");
    }
}
public class Dog extends Animal {
    void sound() {
        System.out.println("Bark");
    }
}


Abstract Classes and Interfaces

Abstract Classes

Can contain both complete and incomplete methods.

public abstract class Shape {
    abstract void draw(); // Abstract method
    void fillColor() { // Non-abstract method
        System.out.println("Filling color...");
    }
}

Interfaces

Must be implemented by classes with all methods defined.

public interface Flyable {
    void fly();
}
public class Bird implements Flyable {
    public void fly() {
        System.out.println("Bird is flying");
    }
}


Design Principles and Patterns

  • Principles like robustness, adaptability, and reusability guide software development.
  • Design patterns such as Iterator, Adapter, and Factory method address common problems in software design.


Exception Handling

Definition

Java uses exceptions to manage errors and other exceptional events effectively.

try {
    int[] numbers = {1, 2, 3};
    System.out.println(numbers[5]); // Will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("An error occurred: " + e.getMessage());
}




Back to Top

See other articles in Category Java

Leave a comment