Sunday, June 1, 2025

JAVA Coding

// This is a simple Java program that simulates a car's basic behavior. public class Car { // Fields (also called instance variables) to store the car's attributes private String brand; private int speed; // Constructor: This sets up the car with initial values public Car(String brand) { this.brand = brand; this.speed = 0; // Car starts stationary } // Method to accelerate the car public void accelerate(int increaseBy) { speed += increaseBy; System.out.println(brand + " accelerated to " + speed + " km/h."); } // Method to brake the car public void brake(int decreaseBy) { if (speed - decreaseBy < 0) { speed = 0; // Prevent negative speed } else { speed -= decreaseBy; } System.out.println(brand + " slowed down to " + speed + " km/h."); } // Method to display current speed public void displaySpeed() { System.out.println("Current speed of " + brand + " is " + speed + " km/h."); } // Main method to run the program public static void main(String[] args) { // Creating a new Car object named 'myCar' Car myCar = new Car("Toyota"); // Simulating some actions myCar.accelerate(50); // Increases speed myCar.displaySpeed(); // Shows current speed myCar.brake(20); // Slows down myCar.displaySpeed(); // Shows new speed } }

No comments:

Post a Comment

Disabled State Structure in Bootstrap

Regulate User Interactions:                                                     A key idea in web development and user interface design, the...