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?
About Question enthuware.ocajp.i.v7.2.876 :
Moderators: Site Manager, fjwalraven
-
- Site Admin
- Posts: 10388
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocajp.i.v7.2.876 :
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.
HTH,
Paul.
-
- Posts: 14
- Joined: Wed Oct 09, 2013 3:13 am
- Contact:
Re: About Question enthuware.ocajp.i.v7.2.876 :
The review shows me that this answer is correct:
Change getArea method to:
This line won't compile since the return type is omitted.
Regards
Bernhard
Change getArea method to:
Code: Select all
public getArea(){ return side*side; }
Regards
Bernhard
-
- Site Admin
- Posts: 10388
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocajp.i.v7.2.876 :
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.
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.
-
- Posts: 14
- Joined: Wed Oct 09, 2013 3:13 am
- Contact:
Re: About Question enthuware.ocajp.i.v7.2.876 :
Hi,
The mistake is in the TRIAL bank not the regular question bank.
Regards,
Bernhard
The mistake is in the TRIAL bank not the regular question bank.
Regards,
Bernhard
-
- Site Admin
- Posts: 10388
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocajp.i.v7.2.876 :
You are right, Bernhard. This has now been fixed.
thank you for your feedback!
Paul.
thank you for your feedback!
Paul.
Who is online
Users browsing this forum: No registered users and 2 guests