How can I design a class in Java called “car” with multiple constructors?

310    Asked by dhanan_7781 in Salesforce , Asked on Feb 27, 2024

I am currently engaged in a particular task that is related to designing a class in Java programming language called “c” with multiple constructors for accommodating different scenarios such as initializing the car with the values that are default and additional features such as advance GPS and leather seats. How can I use the appropriate constructor based on the different situations within your program? 

Answered by Dylan Forsyth

 In the context of Salesforce, you can call a constructor in Java programming language by using the keyword “new” followed by the name of the constructor and any required arguments. Here is how you can call different constructors for the “car” class:-


Public class Car {
    Private String make;
    Private String model;
    Private boolean hasGPS;
    Private boolean hasLeatherSeats;
    // Default constructor
    Public Car() {
        // Initialize default values
        Make = “Toyota”;
        Model = “Corolla”;
        hasGPS = false;
        hasLeatherSeats = false;
    }
    // Constructor with make and model
    Public Car(String make, String model) {
        This.make = make;
        This.model = model;
        hasGPS = false;
        hasLeatherSeats = false;
    }
    // Constructor with make, model, GPS, and leather seats
    Public Car(String make, String model, boolean hasGPS, boolean hasLeatherSeats) {
        This.make = make;
        This.model = model;
        This.hasGPS = hasGPS;
        This.hasLeatherSeats = hasLeatherSeats;
    }
    // Other methods…
    Public static void main(String[] args) {
        // Calling default constructor
        Car defaultCar = new Car();
        // Calling constructor with make and model
        Car specificCar = new Car(“Honda”, “Accord”);
        // Calling constructor with make, model, GPS, and leather seats
        Car featureCar = new Car(“Tesla”, “Model S”, true, true);
    }
}

Your Answer

Interviews

Parent Categories