0
0
Javaprogramming~5 mins

OOP principles overview in Java

Choose your learning style9 modes available
Introduction

OOP helps organize code by grouping related data and actions together. It makes programs easier to build, understand, and change.

When building programs that model real-world things like cars, animals, or users.
When you want to reuse code without rewriting it.
When you want to keep parts of your program separate and easy to fix.
When working on large projects with many programmers.
When you want your program to be easy to grow and add new features.
Syntax
Java
class ClassName {
    // fields (data)
    // methods (actions)
}

A class is like a blueprint for objects.

Objects are created from classes and hold actual data.

Examples
This class has a color and a drive action.
Java
class Car {
    String color;
    void drive() {
        System.out.println("Driving");
    }
}
This class models a dog that can bark.
Java
class Dog {
    String name;
    void bark() {
        System.out.println("Woof!");
    }
}
Sample Program

This program shows inheritance and method overriding. Dog inherits from Animal and changes how speak() works.

Java
class Animal {
    String name;
    void speak() {
        System.out.println(name + " makes a sound");
    }
}

class Dog extends Animal {
    @Override
    void speak() {
        System.out.println(name + " says Woof!");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.name = "Buddy";
        dog.speak();
    }
}
OutputSuccess
Important Notes

Encapsulation means keeping data safe inside classes.

Inheritance lets one class use features of another.

Polymorphism means one action can work in different ways.

Abstraction hides complex details and shows only what is needed.

Summary

OOP groups data and actions into classes and objects.

Four main principles: Encapsulation, Inheritance, Polymorphism, Abstraction.

OOP makes code easier to manage and grow.