Java OOP Concepts
Object-Oriented Programming (OOP) is a programming paradigm that uses "objects" to represent data and methods. Java is a popular OOP language that emphasizes four key concepts: Encapsulation, Inheritance, Polymorphism, and Abstraction.
Key Points on OOP:
- OOP promotes code reusability through inheritance.
- Encapsulation protects the state of an object by restricting access to its internal data.
- Polymorphism allows methods to be used in different ways depending on the object type.
- Abstraction simplifies complex systems by exposing only the necessary parts.
1. Encapsulation
Encapsulation is the bundling of data and methods that operate on that data within one unit, usually a class. It restricts access to some components, which can help prevent accidental modification of data.
Code Example:
Code Example: Encapsulation
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Output
2. Inheritance
Inheritance allows a class (child class) to inherit fields and methods from another class (parent class), promoting code reusability and establishing a hierarchy.
Code Example:
Code Example: Inheritance
public class Animal {
public void eat() {
System.out.println("This animal eats food.");
}
}
public class Dog extends Animal {
public void bark() {
System.out.println("The dog barks.");
}
}
Output
Dog dog = new Dog();
dog.eat(); // This animal eats food.
dog.bark(); // The dog barks.
3. Polymorphism
Polymorphism allows methods to have multiple forms based on the object type. It can be achieved through method overloading (same method name, different parameters) and method overriding (same method name, same parameters in subclass).
Code Example:
Code Example: Polymorphism
public class Animal {
public void sound() {
System.out.println("Animal makes a sound");
}
}
public class Cat extends Animal {
@Override
public void sound() {
System.out.println("Cat meows");
}
}
public class Dog extends Animal {
@Override
public void sound() {
System.out.println("Dog barks");
}
}
Output
4. Abstraction
Abstraction is the concept of hiding the complex reality while exposing only the necessary parts. In Java, abstraction can be achieved through abstract classes and interfaces.
Code Example:
Code Example: Abstraction
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing a Circle");
}
}
Output
Shape circle = new Circle();
circle.draw(); // Drawing a Circle
Summary
Understanding and mastering OOP concepts in Java helps in designing and developing scalable and maintainable software systems.