Overview of Nested, Static, Anonymous, Local Inner Classes


<aside> <img src="/icons/table_red.svg" alt="/icons/table_red.svg" width="40px" /> Table of Contents

</aside>

<aside> 💡

  1. Constructors </aside>

<aside> 💡

  1. Methods in Java </aside>

<aside> 💡

  1. Static Keyword </aside>

<aside> 💡

  1. Static Methods </aside>

Constructors in Java


  1. Constructors
    1. Definition

      1. A constructor is a special method in Java used to initialize objects. It is invoked automatically when an object of a class is created.
    2. Key Characteristics

      1. The name of the constructor must match the class name.
      2. It does not have a return type (not even void).
      3. Used to initialize object properties.
    3. Types of Constructors

      1. Default Constructor: Automatically provided by Java if no constructors are explicitly defined.
      2. Parameterized Constructor: Accepts parameters to initialize object properties.
      3. No-argument Constructor: A constructor with no parameters.
    4. Example: Default Constructor

      class Vehicle {
          Vehicle() { // Default constructor
              System.out.println("Vehicle created.");
          }
      }
      
      public class Main {
          public static void main(String[] args) {
              Vehicle v = new Vehicle(); // Constructor called
          }
      }
      
    5. Output:

      Vehicle created.
      
    6. Example: Parameterized Constructor

      class Vehicle {
          String name;
      
          Vehicle(String name) { // Parameterized constructor
              this.name = name;
          }
      
          void display() {
              System.out.println("Vehicle Name: " + name);
          }
      }
      
      public class Main {
          public static void main(String[] args) {
              Vehicle car = new Vehicle("Car");
              car.display();
          }
      }
      
    7. Output:

      Vehicle Name: Car