Monday, July 27, 2009

Which is true about the initialization of the instance fields?

Suppose the Car class has the following instance field declarations.





private double mileage; // mileage on odometer


private double mpg; //.Miles per gallon


private double tankSize; // Size of gas tang in gallons





A) the instance fields must be intialized in the constructor. If they are not, there will be a compile-time error.


B)The instance fields must be initialized in the constructor. If they are not, the program will compile but there will be a run-time erroe when the car object constructor is called.


C) something else (explain)


C)


D)


E)

Which is true about the initialization of the instance fields?
It looks like you are using Java. Here, we define "int i" but never initialize it.





class hello {


public static void main(String[] args) {


int i;


System.out.println(i);


} // End Main


} // End Class





When I try to compile it:





$ javac hello.java


hello.java:4: variable i might not have been initialized


System.out.println(i);


^


1 error





So there you go. The problem is on line 3 when the variable is defined but the compiler tells me line 4 when the variable is used.





So, compile-time error will be generated if a instance variable is used but never initialized. You can define instance variables and never use them to avoid the compiler error, but what's the point in that?
Reply:Without telling us what language, all we can do is guess. Different languages and compilers treat these problems differently (or not at all). C# will complain, I don't know about Java and C++ will usually not complain or give you an error.


No comments:

Post a Comment