I got an annoying question why is it when I first attempted to compile this code with the variables imageSize and memorySize declared immediately under CameraPhone class compiler gave me a logic error but works perfectly when I declare the variables at the end of the code???
Assume the existence of a Phone class. Define a subclass, CameraPhone that contains two instance variables: an integer named, imageSize, representing the size in megapixels (for simplicity assume a pixel takes up one byte– thus megapixels equals megabytes) of each picture (i.e., 2 means each image is composed of 2 megapixels), and an integer named memorySize, representing the number of gigabytes in the camera’s memory (i.e., 4 means 4 Gigabyes of memory). There is a constructor that accepts two integer parameters corresponding to the above two instance variables and which are used to initialize the respective instance variables. There is also a method named numPictures that returns (as an integer) the number of pictures the camera’s memory can hold. Don’t forget that a gigabyte is 1,000 megabytes.
public class CameraPhone extends Phone {
public CameraPhone(int imageSize, int memorySize) {
this.imageSize = imageSize;
this.memorySize = memorySize;
}
public int numPictures() {
return memorySize * 1000 / imageSize;
}
private int imageSize; private int memorySize;
}
And what’s the “logic error” that you were getting? If you copy and paste the code in the question it will work without problems, it doesn’t matter at all where yo declared the attributes (a.k.a. “instance variables”) – at the beginning, at the end, it’s all the same as long as you actually declared and initialized them somewhere. What I mean is that as long as these lines appear anywhere inside the class declaration (not inside a method, mind you) the code will compile:
Also, it’s perfectly legal to use
thisinside a constructor, that is not causing the error. And the attributes can be initialized directly where you declared them, or inside the constructor.