Menu
Coddy logo textTech

Introduction to OOP

Part of the Object Oriented Programming section of Coddy's Java journey — lesson 2 of 87.

Object-Oriented Programming (OOP) is a way to structure code using objects that contain data and behavior.

A class is a blueprint

public class Animal {
    String name;
    
    public Animal(String name) {
        this.name = name;
    }
    
    public String makeSound() {
        return this.name + " makes a sound!";
    }
}

An object is an instance created from the blueprint

Animal dog = new Animal("Buddy");
System.out.println(dog.makeSound());

Output:

Buddy makes a sound!

OOP lets you model real-world things as objects. Each object has data (fields) and actions (methods). The four pillars of OOP are Encapsulation, Inheritance, Polymorphism, and Abstraction.

challenge icon

Challenge

Easy

Create an Animal class that demonstrates the basics of OOP:

  • A name field (String)
  • A constructor that sets the name
  • A makeSound() method that returns "<name> makes a sound!"

Cheat sheet

Object-Oriented Programming (OOP) structures code using objects that contain data and behavior.

A class is a blueprint for creating objects:

public class Animal {
    String name;
    
    public Animal(String name) {
        this.name = name;
    }
    
    public String makeSound() {
        return this.name + " makes a sound!";
    }
}

An object is an instance created from a class:

Animal dog = new Animal("Buddy");
System.out.println(dog.makeSound());

Objects have data (fields) and actions (methods). The four pillars of OOP are Encapsulation, Inheritance, Polymorphism, and Abstraction.

Try it yourself

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String name = scanner.nextLine();
        
        Animal animal = new Animal(name);
        
        System.out.println("Animal name: " + animal.name);
        System.out.println(animal.makeSound());
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming