About Question enthuware.ocajp.i.v7.2.876 :
Posted: Mon May 14, 2012 1:42 am
Consider the following two classes (in the same package but defined in different source files):
public class Square {
double side = 0;
double area;
public Square(double length){ this.side = length; }
public double getSide() { return side; }
public void setSide(double side) { this.side = side; }
double getArea() { return area; }
}
public class TestClass {
public static void main(String[] args) throws Exception {
Square sq = new Square(10.0);
sq.area = sq.getSide()*sq.getSide();
System.out.println(sq.getArea());
}
}
You are assigned the task of refactoring the Square class to make it better in terms of encapsulation. What changes will you make to this class?
one option suggested is
Make side and area fields private.
that option is wrong as TestClass is accessing area field through object ie sq.area = sq.getSide()*sq.getSide(); doing so will occur compilation error in specified line?
Please advise?
public class Square {
double side = 0;
double area;
public Square(double length){ this.side = length; }
public double getSide() { return side; }
public void setSide(double side) { this.side = side; }
double getArea() { return area; }
}
public class TestClass {
public static void main(String[] args) throws Exception {
Square sq = new Square(10.0);
sq.area = sq.getSide()*sq.getSide();
System.out.println(sq.getArea());
}
}
You are assigned the task of refactoring the Square class to make it better in terms of encapsulation. What changes will you make to this class?
one option suggested is
Make side and area fields private.
that option is wrong as TestClass is accessing area field through object ie sq.area = sq.getSide()*sq.getSide(); doing so will occur compilation error in specified line?
Please advise?