OOPs in java
1. Encapsulation
Encapsulation is the bundling of data (attributes) and methods (functions) that operate on the data into a single unit, usually a class. It restricts direct access to some of the object’s components.
class Person {
// Private variables
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter for name
public String getName() {
return name;
}
// Setter for name
public void setName(String name) {
this.name = name;
}
// Getter for age
public int getAge() {
return age;
}
// Setter for age
public void setAge(int age) {
this.age = age;
}
}
public class EncapsulationExample {
public static void main(String[] args) {
Person person = new Person("Alice", 30);
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
// Update name and age
person.setName("Bob");
person.setAge(35);
System.out.println("Updated Name: " + person.getName());
System.out.println("Updated Age: " + person.getAge());
}
}2. Inheritance
Inheritance allows a class to inherit properties and methods from another class.
class Animal {
public void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
public void bark() {
System.out.println("The dog barks.");
}
}
public class InheritanceExample {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Inherited method
dog.bark(); // Dog's own method
}
}
3. Polymorphism
Polymorphism allows methods to do different things based on the object it is acting upon. It can be achieved through method overriding and method overloading.
Get Harshh🎀’s stories in your inbox
Join Medium for free to get updates from this writer.
Method Overriding Example:
class Animal {
public void sound() {
System.out.println("Animal makes a sound");
}
}
class Cat extends Animal {
@Override
public void sound() {
System.out.println("Cat meows");
}
}
class Dog extends Animal {
@Override
public void sound() {
System.out.println("Dog barks");
}
}
public class PolymorphismExample {
public static void main(String[] args) {
Animal myCat = new Cat();
Animal myDog = new Dog();
myCat.sound(); // Output: Cat meows
myDog.sound(); // Output: Dog barks
}
}4. Abstraction
Abstraction is the concept of hiding the complex implementation details and showing only the essential features of the object.
abstract class Shape {
abstract void draw(); // Abstract method
}
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a Circle");
}
}
class Rectangle extends Shape {
@Override
void draw() {
System.out.println("Drawing a Rectangle");
}
}
public class AbstractionExample {
public static void main(String[] args) {
Shape circle = new Circle();
Shape rectangle = new Rectangle();
circle.draw(); // Output: Drawing a Circle
rectangle.draw(); // Output: Drawing a Rectangle
}
}







