76 311
Assignments Done
98,1%
Successfully Done
In May 2019

Answer to Question #47463 in Java | JSP | JSF for Alala

Question #47463
Consider the following implementation of a class Square:

public class Square
{
privateintsideLength;
privateint area; // Not a good idea

public Square(int length){
sideLength = length;
}
publicintgetArea(){
area = sideLength * sideLength;
return area;
}
}

Why is it not a good idea to introduce an instance variable for the area? Rewrite the class so that area is a local variable.
Expert's answer
public class Square {

private intsideLength;
private intarea; // Not a good idea

publicSquare(int length) {
sideLength = length;
}

public intgetArea() {
area =sideLength * sideLength;
returnarea;
}

/* it is abad idea because if you add mutator and accessor to your fields
then youneed always to recalculate area during setSideLength method invocation
*/
public intgetSideLength() {
returnsideLength;
}

public voidsetSideLength(int sideLength) {
this.sideLength = sideLength;
area =sideLength * sideLength; //here is problem root, you need to update state of
object instantly!
}

}


Howit must be:


public class Square {

private intsideLength;

publicSquare(int length) {
sideLength = length;
}

public intgetArea() {
returnsideLength * sideLength;
}

public intgetSideLength() {
return sideLength;
}

public voidsetSideLength(int sideLength) {
this.sideLength = sideLength;
}

}


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions