Page 1 of 1

About Question enthuware.ocajp.i.v7.2.876 :

Posted: Mon May 14, 2012 1:42 am
by bahadur baniya
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?

Re: About Question enthuware.ocajp.i.v7.2.876 :

Posted: Mon May 14, 2012 3:31 pm
by admin
You are right. It will not compile but that is ok because you don't want to permit such direct access. That is the whole purpose of this refactoring.

HTH,
Paul.

Re: About Question enthuware.ocajp.i.v7.2.876 :

Posted: Wed Oct 09, 2013 3:27 am
by thisOtterBeGood
The review shows me that this answer is correct:

Change getArea method to:

Code: Select all

public getArea(){ return side*side; }
This line won't compile since the return type is omitted.

Regards
Bernhard

Re: About Question enthuware.ocajp.i.v7.2.876 :

Posted: Wed Oct 09, 2013 6:04 am
by admin
Hi Bernhard,
Please make sure you are using the latest version of the question bank because I see that this option was fixed quite a while ago.

HTH,
Paul.

Re: About Question enthuware.ocajp.i.v7.2.876 :

Posted: Thu Oct 10, 2013 6:23 am
by thisOtterBeGood
Hi,
The mistake is in the TRIAL bank not the regular question bank.

Regards,
Bernhard

Re: About Question enthuware.ocajp.i.v7.2.876 :

Posted: Thu Oct 10, 2013 7:34 am
by admin
You are right, Bernhard. This has now been fixed.

thank you for your feedback!
Paul.