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
}
}
Subscribe to:
Post Comments (Atom)
Disabled State Structure in Bootstrap
Regulate User Interactions: A key idea in web development and user interface design, the...
-
Dockerfile Language: Dockerfile is a specialized scripting language used to automate the creation of Docker images, wh...
-
C Tags: Tags are essential for creating unique data structures in the C programming language, which enables programmers to m...
No comments:
Post a Comment