Java OOPs Concepts with Examples
1. Class and Object
A class is a blueprint for objects. An object is an instance of a class.
Example:
class Car {
String color;
void drive() {
System.out.println("Car is driving");
2. Inheritance
Inheritance allows one class to acquire properties of another.
Example:
class Animal {
void eat() { System.out.println("Eating..."); }
class Dog extends Animal {
void bark() { System.out.println("Barking..."); }
3. Polymorphism
Polymorphism means many forms. Method overloading and overriding are examples.
Example:
class Demo {
void show(int a) {}
void show(String b) {}
}
4. Abstraction
Abstraction hides complexity by showing only essential details.
Example:
abstract class Shape {
abstract void draw();
5. Encapsulation
Encapsulation is wrapping data and code into a single unit.
Example:
class Person {
private String name;
public String getName() { return name; }
public void setName(String n) { name = n; }