Question 2: Three errors have occurred while running the following program. Expl
ID: 3876345 • Letter: Q
Question
Question 2: Three errors have occurred while running the following program. Explain why in detail and Correct the errors. class Car4 string color; string geartype: int door: int year; CarType (String c, String g, int door, String year) f color-c; gearlype.= g; door door; year = year;) public class Constructor8 t public static void main(String[] args) Car4 cl new Car4 ("white", "auto", "4", 2018) ; System.out.print.ln ("my car: " cl.color + cl.gearType "" c1.door + "" rt I +cl.year); /* explain why in detailExplanation / Answer
PROGRAM AND SOLUTION
import java.io.*;
class Car4
{
String color; String gearType; // Declare String variables
int door; // Delcare integer variable
String year; // Delcare String variable
Car4(String c,String g,int door, String year) // Create Constructor, the constructor name should be class name Car4
{
color=c; gearType=g; // assign String variable to data members
this.door=door; this.year=year; // assign same variable name by using "this" opearator
}
}
public class Constructor8
{
public static void main(String[]args)
{
Car4 c1=new Car4("white","auto",4,"2018"); // Create object and define constant values
System.out.println("my car: "+c1.color+" , "+c1.gearType+" , "+c1.door+" , "+c1.year); // Display actual values
}
}
OUTPUT:
java Constructor8
my car: white , auto , 4 , 2018
Solution:
1. The Constructor should be declare same name of class name(such as Car4 is class name constructor should be Car4).
2. In the constructor the parameter are "Car3(String c,String g,int door,String year)" , the class members and constructor parameter is same that should be access by "this" opeartor, then you should be use "this.door=door and this.year=year".
3. The main class create object "c1", actual values shoule be ("white","auto",4,"2018"), then the first two paratemer are String values and next integer and String value. So, the year parameter should be String in member varible(i.e., String year in member variable).
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.