Header Ads

Write a program in java which will have two classes i.e., Vehicle and Asssignment1 class.

Write a program in java which will have two classes i.e., Vehicle and Asssignment1 class. Vehicle class will have three data members (name, price, model), a default constructor, a parameterized constructor, setter and getter functions and a display () function. Assignment1 class will contains main method.

In main method you are required to create two objects of vehicle class by giving parameters for name, price and model. Create first object using parameterized constructor and second object by using default constructor & setter functions. After creating these objects store both objects in the ArrayList then print your student id and ArrayList objects data on console using for loop and display() function of Vehicle class.

Details: (Assignment1.java file contains)

1. Vehicle class

Data Members: name, price, model

Default Constructor: Vehicle

Parametrized Constructor: Vehicle (name, price, model)

Setter Functions: setName(…), setPrice(…), setModel(…)

Getter Functions: getName(), getPrice(), getModel()

Display Function: display()

2. Assignment1 class

Main Method: public String void main(String args[])

Solution:

Vehicle.java:

public class Vehicle {

    private String name;

    private double price;

    private int model;


    public Vehicle() {

    }


    public Vehicle(String name, double price, int model) {

        this.name = name;

        this.price = price;

        this.model = model;

    }


    public void setName(String name) {

        this.name = name;

    }


    public void setPrice(double price) {

        this.price = price;

    }


    public void setModel(int model) {

        this.model = model;

    }


    public String getName() {

        return name;

    }


    public double getPrice() {

        return price;

    }


    public int getModel() {

        return model;

    }


    public void display() {

        System.out.println("Name: " + name);

        System.out.println("Price: " + price);

        System.out.println("Model: " + model);

    }

}

Assignment1.java:

import java.util.ArrayList;


public class Assignment1 {

    public static void main(String[] args) {

        Vehicle vehicle1 = new Vehicle("Toyota Camry", 25000.0, 2021);


        Vehicle vehicle2 = new Vehicle();

        vehicle2.setName("Honda Civic");

        vehicle2.setPrice(22000.0);

        vehicle2.setModel(2022);


        ArrayList<Vehicle> vehicles = new ArrayList<>();

        vehicles.add(vehicle1);

        vehicles.add(vehicle2);


        System.out.println("Student ID: YOUR_STUDENT_ID");

        for (Vehicle vehicle : vehicles) {

            vehicle.display();

        }

    }

}


No comments

Powered by Blogger.