Category : Java | Sub Category : Object- oriented Programming | By Prasad Bonam Last updated: 2023-07-31 00:56:43 Viewed : 639
In Java, Object-Oriented Programming (OOP) is a fundamental programming paradigm that revolves around the concept of objects. OOP helps in organizing code in a more modular and reusable manner. There are four main pillars of OOP in Java:
Example:
javapublic class Person {
private String name;
private int age;
// Getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Example:
javapublic class Animal {
public void makeSound() {
System.out.println("Some generic animal sound.");
}
}
public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Bark! Bark!");
}
}
Example of method overloading (compile-time polymorphism):
javapublic class MathOperations {
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
}
Example of method overriding (runtime polymorphism):
javapublic class Animal {
public void makeSound() {
System.out.println("Some generic animal sound.");
}
}
public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Bark! Bark!");
}
}
public class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow!");
}
}
Example of abstract class:
javapublic abstract class Shape {
public abstract double calculateArea();
}
Example of an interface:
javapublic interface Drawable {
void draw();
}
These OOP concepts help developers to create well-organized, modular, and maintainable code by promoting code reuse, reducing complexity, and enhancing flexibility.