1. Encapsulation in Java
Encapsulation is the process of wrapping code and data together into a single unit. In Java, encapsulation is achieved using classes and access modifiers.
Example:
class Student { private String name; private int age; 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; } }
2. Polymorphism in Java
Polymorphism allows methods to do different things based on the object it is acting upon. It can be achieved through method overloading and method overriding.
Example:
class Animal { public void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { @Override public void sound() { System.out.println("Dog barks"); } } class Cat extends Animal { @Override public void sound() { System.out.println("Cat meows"); } }
3. Abstraction in Java
Abstraction is the concept of hiding the internal details and showing only the functionality. It can be achieved using abstract classes and interfaces.
Example:
abstract class Shape { abstract void draw(); } class Circle extends Shape { void draw() { System.out.println("Drawing Circle"); } } class Rectangle extends Shape { void draw() { System.out.println("Drawing Rectangle"); } }
4. Inheritance in Java
Inheritance is a mechanism where one class acquires the properties and behaviors of a parent class. It provides code reusability.
Example:
class Person { String name; int age; } class Student extends Person { int studentId; }
5. Difference Between Encapsulation And Abstraction in Java
Encapsulation is about bundling the data and methods that operate on the data into a single unit, while abstraction is about hiding the implementation details and showing only the functionality.
6. Method Overloading in Java
Method overloading is a feature that allows a class to have more than one method with the same name, but different parameters.
Example:
class MathUtils { public int add(int a, int b) { return a + b; } public double add(double a, double b) { return a + b; } }
7. Method Overriding in Java
Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass.
Example:
class Vehicle { void run() { System.out.println("Vehicle is running"); } } class Bike extends Vehicle { @Override void run() { System.out.println("Bike is running"); } }
8. Association, Aggregation And Composition in Java
Association is a relationship between two objects. Aggregation is a special form of association where one object contains other objects. Composition is a stronger form of aggregation where the contained objects cannot exist without the container object.
Example:
class Library { private String name; private Listbooks; } class Book { private String title; private String author; }