Java – Sealed Classes (Java 17+)
Sealed Classes: Restricts which classes can extend or implement a class/interface.Example: sealed class Shape permits Circle, Rectangle { }final class Circle extends Shape { }final class Rectangle extends Shape { }
Sealed Classes: Restricts which classes can extend or implement a class/interface.Example: sealed class Shape permits Circle, Rectangle { }final class Circle extends Shape { }final class Rectangle extends Shape { }
Functional Interfaces: An interface with a single abstract method. Used with Lambda Expressions.Example: @FunctionalInterfaceinterface Greeting { void sayHello(String name);}Greeting greet = (name) -> System.out.println("Hello, " + name);greet.sayHello("John");
Streams: Used for processing collections with declarative programming. Supports operations like map, filter, reduce.Example: List numbers = Arrays.asList(1, 2, 3, 4, 5);numbers.stream() .filter(n -> n % 2 == 0) .forEach(System.out::println);
Default Methods: Allows interfaces to have concrete methods with default implementation.Example: interface Vehicle { default void start() { System.out.println("Vehicle is starting."); }}class Car implements Vehicle {}Car myCar = new Car();myCar.start();
Records: Simplifies creating immutable data classes. Automatically generates constructors, equals, hashCode, and toString.Example: record Person(String name, int age) {}Person p = new Person("Alice", 25);System.out.println(p.name() + ", " + p.age());
Pattern Matching: Simplifies conditional code by type-checking in expressions.Example: Object obj = "Hello";if (obj instanceof String str) { System.out.println(str.toUpperCase());}
Object-Oriented Programming (OOP): Java follows OOP principles: Encapsulation, Inheritance, Polymorphism, and Abstraction. These principles help in building modular, scalable, and maintainable applications.
Encapsulation: Restricting direct access to object data and methods by using private access modifiers and providing public getters and setters.Example: class Employee { private String name; private int id; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int […]
Inheritance: Enables one class to acquire the properties and behavior of another class using the extends keyword.Example: class Animal { void eat() { System.out.println("This animal eats food."); }}class Dog extends Animal { void bark() { System.out.println("Dog barks."); }}Dog myDog = new Dog();myDog.eat();myDog.bark();
Polymorphism: The ability of a method to perform different tasks based on its parameters or the object it is called on. Types: Method Overloading and Method Overriding.Example:Overloading: class MathOps { int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; }}MathOps ops = new […]