Java OOPs Concepts with Examples
1. Class and Object
A class is a blueprint for creating objects. An object is an instance of a class.
Example:
class Car {
String color;
void drive() {
System.out.println("Car is driving");
Car obj = new Car();
obj.drive();
2. Inheritance
Inheritance allows a class to acquire properties and behavior from another class.
Example:
class Animal {
void sound() {
System.out.println("Animal sound");
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
Java OOPs Concepts with Examples
3. Polymorphism
Polymorphism means one name many forms. It can be achieved by method overloading or overriding.
Example:
class Shape {
void draw() {
System.out.println("Drawing shape");
class Circle extends Shape {
void draw() {
System.out.println("Drawing circle");
4. Abstraction
Abstraction is hiding internal details and showing functionality only.
Example:
abstract class Animal {
abstract void makeSound();
class Cat extends Animal {
void makeSound() {
System.out.println("Meow");
}
Java OOPs Concepts with Examples
5. Encapsulation
Encapsulation is binding data and methods together and hiding the data.
Example:
class Student {
private String name;
public String getName() { return name; }
public void setName(String n) { name = n; }