Q:

java OOP simple composition example Car class and Engine class

0

Define a class named Engine containing:

An instance variable named engineNo of type string, initialized to null. 

A full parameterized contructor.

A method named getEngineNo that returns the value of engineNo. 

A method named start that starts the engine via displaying the message "Start the car".

A method named rev that reverse the enginevia displaying the message "Reverse the engine".

A method named stop that stops the enginevia displaying the message "Car stopped".

 

Define another class named Car containing:

An instanc variable named name of type string, initialized to null.

An instance object named engine of type Engine

A full parameterized constructor.

A method named move that invokes the method start of the object engine for moving the car. 

A method named goBack that invokes the method rev of the object engine for reversing the car

A method named stop that invokes the method stop of the object engine for stopping the car.

A method named display that prints all car's data (i.e. car name and engine number).

Define a third class named TestCar contains a main method that test the functionality of the above

classes.

Composition : using objects as attributes in new classes.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

public class TestCar
{
    public static void main(String[] args) {
        Car ca=new Car("Lada","22352");
        ca.display();
    }
}
class Engine
{
    String enginNo=null;
    public Engine(String EngNo)
    {
        enginNo=EngNo;
    }
    
    public String getEngeneNo()
    {
        return enginNo;
    }
    public void Start()
    {
        System.out.println("Start the Car");
    }
    public void Reverse()
    {
        System.out.println("Reverse the engine");
    }
    public void Stop()
    {
        System.out.println("Car stopped");
    }
}

class Car
{
    String name=null;
    Engine engine;
    public Car(String Name,String Engno)
    {
        name=Name;
        engine=new Engine(Engno);
    }
    public void move()
    {
        engine.Start();
    }
    public void goBack()
    {
        engine.Reverse();
    }
    public void Stop()
    {
        engine.Stop();
    }
    public void display()
    {
        System.out.println("Engine Num : "+engine.getEngeneNo()+" ,Car Name :"+this.name);
    }
    
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now