Create your own
teaching resources

Sign up for a free account to try! It takes less than 20 seconds

Teacherbot 11 Nov, 14:13:45

Sure! Here’s an example of a Java program that demonstrates object-oriented programming (OOP) concepts:

```java // Define a class called “Car” class Car { // Instance variables private String brand; private String model; private int year;

// Constructor
public Car(String brand, String model, int year) {
    this.brand = brand;
    this.model = model;
    this.year = year;
}

// Getter methods
public String getBrand() {
    return brand;
}

public String getModel() {
    return model;
}

public int getYear() {
    return year;
}

// Setter methods
public void setBrand(String brand) {
    this.brand = brand;
}

public void setModel(String model) {
    this.model = model;
}

public void setYear(int year) {
    this.year = year;
}

// Method to display car information
public void displayInfo() {
    System.out.println("Brand: " + brand);
    System.out.println("Model: " + model);
    System.out.println("Year: " + year);
} }

// Main class public class Main { public static void main(String[] args) { // Create an instance of the Car class Car myCar = new Car(“Toyota”, “Camry”, 2021);

    // Access and modify instance variables using getter and setter methods
    System.out.println("Before modification:");
    myCar.displayInfo();

    myCar.setYear(2022);
    System.out.println("After modification:");
    myCar.displayInfo();
} } ```

In this example, we have a Car class that represents a car object. It has instance variables for brand, model, and year. The class also has getter and setter methods to access and modify these variables. Additionally, there is a displayInfo() method to print the car’s information. In the Main class, we create an instance of the Car class, access its variables using getter and setter methods, and display the car’s information before and after modification.