w3resource

Java Program with Local Class in Method - Car and Engine

Java Nested Classes: Exercise-3 with Solution

Local Class:
Write a Java program to create a class called Car with a method startEngine(). Inside this method, define a local class Engine that has a method run(). The run() method should print "Engine is running". Instantiate and call the run() method from within the startEngine() method.

Sample Solution:

Java Code:

Car.java

// Class Car
public class Car {
    
    // Method startEngine
    public void startEngine() {
        // Local class Engine inside startEngine method
        class Engine {
            // Method run in local class Engine
            public void run() {
                // Print statement indicating the engine is running
                System.out.println("Engine is running");
            }
        }
        
        // Creating an instance of the local class Engine
        Engine engine = new Engine();
        // Calling the run method of the local class Engine
        engine.run();
    }
    
    // Main method to demonstrate the local class
    public static void main(String[] args) {
        // Creating an instance of Car
        Car myCar = new Car();
        // Calling the startEngine method
        myCar.startEngine();
    }
}

Output:

Engine is running

Explanation:

  • Class Car: The outer class that contains the method startEngine().
  • Method startEngine(): This method contains the local class Engine.
  • Local class Engine: Defined within the startEngine() method and has a method run().
  • Method run(): Prints "Engine is running".
  • Instantiate Engine: Inside startEngine(), an instance of the local class Engine is created and the run() method is called.
  • Main method: Demonstrates the usage of the local class by creating an instance of Car and calling the startEngine() method.

Note on Java Nested Classes:

Java nested classes allow for different levels of nested class usage. Local classes are defined within a block, typically a method, and can only be accessed within that block. In this exercise, the Engine class is a local class within the startEngine() method of the Car class, allowing it to encapsulate the logic for starting the engine within that method. This enhances code organization and encapsulation.

Java Code Editor:

Improve this sample solution and post your code through Disqus.

Java Static Members Previous: Java Program for Static Nested Class - University and Department.
Java Static Members Next: Java Anonymous Class Implementing an Interface Example.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-exercises/nested-classes/java-nested-classes-exercise-3.php