Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The following class displays a disclaimer every time an instance is created usin

ID: 3828998 • Letter: T

Question

The following class displays a disclaimer every time an instance is created using the default constructor :

public class Vehicle {
public Vehicle(){
System.out .println("You should not operate this vehicle under the influence of alcohol!");
}
}

However, we would like the disclaimer to appear only once when the very first Vehicle object is created. Any future Vehicle objects that are created should display no disclaimer.

Modify the code to use a static  boolean  variable that is initialized to false when it is defined. The disclaimer should only be displayed if the variable is false , and once the disclaimer is displayed, the variable should be set to true .

Add a main method to the same file and use it to create and initialize three Vehicle objects .

Explanation / Answer

import java.util.*;

import java.lang.*;
import java.io.*;

class Vehicle {
   public static boolean flag=false;
   public Vehicle(){
       if(flag==true){
           System.out .println("");
       }else{
           System.out .println("You should not operate this vehicle under the influence of alcohol!");
           flag=true;
       }
   }
}

class Ideone
{
   public static void main (String[] args) throws java.lang.Exception
   {
       Vehicle v1= new Vehicle();
       Vehicle v2= new Vehicle();
       Vehicle v3= new Vehicle();
      
   }
}

here i have made class Vechile and a boolean value initlise with false, and checked if the boolean value means flag is true the i am printing nothing and if the boolean value is false then just displaying the message and make the flag variable as true. When in main class i have just made the refrence of Vechile class. for the first time the flag value is false the else part will be executed and make the flag value as true and for the next time it always goes in the if part and displaying no message.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote