Is this proper encapsulation for this Java code? I am confused - java

Does this Java code involving a Book class use proper encapsulation? I feel it can be a lot simpler if I omit some methods but we're required to every method that is in there [especially setters and getters].
Here's the first class:
public class Book
{
private String title;
private double price;
private final double SALES_TAX=0.075;
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title=title;
}
public double getPrice()
{
return price;
}
public void setPrice(double price)
{
this.price=price;
}
public double getSalesTax()
{
return SALES_TAX;
}
public double increasePrice(double incresePrice)
{
return incresePrice;
}
public double calculateSales(double sales)
{
return sales;
}
}
And the second class:
public class BookDriver
{
public static void main(String[] args)
{
Scanner keyboard=new Scanner(System.in);
Book bookOne=new Book();
Book bookTwo=new Book();
bookOne.setTitle("Life of Pi");
System.out.print("Enter number to buy of "+bookOne.getTitle()+": ");
bookOne.setPrice(13.50*bookOne.calculateSales(keyboard.nextDouble()));
bookOne.setPrice((bookOne.getPrice()*bookOne.getSalesTax())+bookOne.getPrice());
System.out.print("Cost for "+bookOne.getTitle()+" $");
System.out.printf("%.2f"+"\n",bookOne.getPrice());
bookTwo.setTitle("Harry Potter: The Goblet Of Fire");
System.out.print("Enter number to buy of "+bookTwo.getTitle()+": ");
bookTwo.setPrice(22.00*bookTwo.calculateSales(keyboard.nextDouble()));
bookTwo.setPrice((bookTwo.getPrice()*bookTwo.getSalesTax())+bookTwo.getPrice());
System.out.print("Cost for "+bookTwo.getTitle()+" $");
System.out.printf("%.2f"+"\n",bookTwo.getPrice());
System.out.print("Enter percent increase of "+bookOne.getTitle()+": ");
bookOne.setPrice((bookOne.getPrice()*bookOne.increasePrice(keyboard.nextDouble()))+bookOne.getPrice());
System.out.printf("Cost of "+bookOne.getTitle()+": $"+"%.2f"+"\n",bookOne.getPrice());
System.out.print("Enter percent increase of "+bookTwo.getTitle()+": ");
bookTwo.setPrice((bookTwo.getPrice()*bookTwo.increasePrice(keyboard.nextDouble()))+bookTwo.getPrice());
System.out.printf("Cost of "+bookTwo.getTitle()+": $"+"%.2f"+"\n",bookTwo.getPrice());
keyboard.close();
}
}
I know that this is a lot so I'm not really expecting much in terms of a response but anything would help. Thanks!!

Let's look at the point of encapsulation. You have a Class which consists of properties and methods. The idea behind encapsulation is, you want the methods in your class to be the only way to change the value (state) of the properties. Think of it like this: if some other code in the program wants to change the value of one of the properties, it cannot do it itself, it must ask a method on the class they reside in to do it. That way, you control access to the properties.
The way this is implemented is with getter and setter methods of which you have created a few. A getter method returns the value of the property and a setter method changes it to a new value.
1.
Your getter and setter methods up to increasePrice() are good. You are preventing access to the properties other than from the methods on your class.
2.
increasePrice() only spits out what was passed into it. It doesn't change the value of any of the properties and thus has no purpose. If you want to be able to increase the price you can change the method like so:
public void increasePrice(double amountOfPriceIncrease) {
price += amountOfPriceIncrease;
/*
price += amountOfPriceIncrease is the same as
price = price + amountOfPriceIncrease
*/
}
3.
This line is a bit troubling. For starters, increasePrice() doesn't do anything other than spit out what was put into it and secondly, there is a lot going on in the one line that makes it complicated and hard to follow.
bookTwo.setPrice((bookTwo.getPrice()*bookTwo.increasePrice(keyboard.nextDouble()))+bookTwo.getPrice());

You dont necessarily need all the setters. For example, its probably reasonable to assume that a book has a title, and it doesnt change. So you can make it final, omit the setter, and pass it into the constructor.
Also, think about how you're modelling things. Is sales tax a property of a book? I'd say not.

Because all the required variables title, price for class Book are set to private, and that access can only be used using get..(), and changing it if possible can only be used using set..(some variable) or an instance method affecting one of the fields, it demonstrates proper encapsulation, so all getting and setting are regulated.
However, I spotted several mistakes in BookDriver, namely with the improper usage of Book fields.
The price should change only through setPrice or increasePrice.
You should also implement getPriceAfterTax to determine after-tax prices for a book.
The total cost of the books you bought should not involve any setPrice.
There is a mistake with public double calculateSales(double sales). It does nothing but returns back sales. The calculateSales should calculate the total cost of the book(s) being bought, using one int variable, and you also resorted in changing the price of these books, which shouldn't happen. It is the reason why you wrote messy code, as in the excerpt
bookTwo.setPrice(22.00*bookTwo.calculateSales(keyboard.nextDouble()));
bookTwo.setPrice((bookTwo.getPrice()*bookTwo.getSalesTax())+bookTwo.getPrice());
This avoids the potential case of changing the values of that BOOK object to unexpected or unusual values and value combinations.
Additionally, SALES_TAX can be made into a public static final double instead, as it is assumed to never change, and you can simply obtain SALE_TAX without requiring getSalesTax().

The last two methods do not make much sense. You simply return what you put in. Do it this way:
public double increasePrice(double increase)
{
price *= increase;
}
public double calculateSales(double sales)
{
//return {your formula}
}

Related

Set & Get Methods

Java I student here!
I am having a hard time understanding how to make set and get methods. I am working on a question in my textbook Java Programming, 9th Edition independently and I am asked to do the following:
"Create a class named Sandwich. Data fields include a String for the main ingredient (such as tuna), a String for bread type (such as wheat), ad a double for price (such as 4.99). Include methods to get and set values for each of these fields."
It then asks me to do this:
"Create an application named TestSandwich that instantiates one Sandwich object and demonstrates the use of the set and get methods."
So for the first part, I made a .java file with the following code:
public class Sandwich {
private String ingredient;
private String bread;
private double price;
public Sandwich(String ing, String bre, double pri) {
ingredient = ing;
bread = bre;
price = pri;
}
public void setIngredient(String ing) {
this.ingredient = ing;
}
public String getIngredient() {
return ingredient;
}
public String getBread() {
return bread;
}
public Double getPrice() {
return price;
}
}
For the second part, I did the following:
import java.util.Scanner;
public class TestSandwich {
public static void main(String[] args) {
String Ingredient;
String Bread;
Double Price;
Scanner keyboard = new Scanner(System.in);
System.out.println("MAKE A SANDWICH");
System.out.println("Enter an ingredient: ");
Ingredient = keyboard.nextLine();
System.out.println("Enter bread: ");
Bread = keyboard.nextLine();
System.out.println("Enter a price");
Price = keyboard.nextDouble();
Sandwich obj = new Sandwich(Ingredient, Bread, Price);
System.out.println("The ingredient is " + obj.getIngredient());
System.out.println("The bread is " + obj.getBread());
System.out.println("The price is " + obj.getPrice());
}
}
I completed this and it works well, however I realize that I did not create any set methods. Could someone explain to me a better way to do this according to the directions? I'm sure that this way works but I would like to do it by the book and be able to understand it better. I'm not sure where to start with creating the set methods. Please let me know. Thanks so much!
PS: This is NOT homework, I'm just trying to understand this a little better.
-Mark
Here you create an object with these values
Sandwich obj = new Sandwich(Ingredient, Bread, Price);
Here you create an empty object and then set the values
Sandwich obj = new Sandwich();
obj.setIngredient(Ingredient);
obj.setBread(Bread);
obj.setPrice(Price);
Consider this code in your class named Sandwich :
public Sandwich(String ing, String bre, double pri) {
ingredient = ing;
bread = bre;
price = pri;
}
This is called a constructor, a special kind of method that is having the same name as that of the class. But it does not return a value. This constructor is accepting three parameters, of which two are strings and one is a double value. In the constructor body you are actually setting values that are passed to the constructor as parameters and so you can consider this as a setter method which is setting three values at once.
Now consider this code inside the same class :
public void setIngredient(String ing) {
this.ingredient = ing;
}
This method is a setter method which sets only one value, i.e. ingredient. You can create other setter methods as well like this giving any name you want to. For example setBread and setPrice method inside the Sandwich class as follows:
public setBread(String bre) {
bread = bre;
}
public setPrice(double pri) {
price = pri;
}
You can either use the constructor to set the values or the "setter methods"(It is just a normal method that is used to accept and set the values). You can use a single method to set all the values in one go, which is what the constructor is doing or use individual methods to set each values like the setter methods we have defined.
If you are using a single method to set all values at once(in this case the constructor) then during the time of instantiating Sandwich class you need to pass all the values at once to the constructor like you did this :
Sandwich obj = new Sandwich(Ingredient, Bread, Price);
If you do not pass three variables to the constructor at once in the correct order, then compilation error will occur. As you already have a constructor setting three values, the other setter methods are not of great use except when you need to change the values afterwards. I hope this helps.
Simple go like:
System.out.println("Enter another price");
double newPrice = keyboard.nextDouble();
obj.setPrice(newPrice);
and print your obj before / after that call (and of course: #Overwrite toString() on that class to get meaningful output).

class method to ask for userinput

I am really pretty new to java and have a homework assignment due in a couple days. Unfortunately when my teacher try's to help me out I just still don't understand it. I need to create two classes to compute a discounted loan and then a main class to call them all and actually make it work. This is my first class its all correct based on what the teacher wants.
package Project2;
public class Loan {
public double money;
public double interest;
public double loanperiod;
public double totaldiscount;
public Loan(){
money=0;
interest=0;
loanperiod=0;
}
//set money,interest,and loanperiod
public void setmoney(double newmoney){
money=newmoney;
}
public void setinterest(double newinterest){
interest=newinterest;
}
public void setloanperiod(double newloanperiod){
loanperiod=newloanperiod;
}
//get money,interest,and loanperiod
public double getmoney(){
return money;
}
public double getinterest(){
return interest;
}
public double getloanperiod(){
return loanperiod;
}
public double gettotaldiscount(){
return totaldiscount;
}
}
The second class I need to create another object. Then I have to create a method to compute the discounted loan and a method to describe the program, a method to get userinputs and a method calling the correct method from from the loan class above to display the output.
So far this is what I have for the second class, just a description method. But I am really confused as to how I am going to make a method to compute the discountedloan (I have the formula), and how to create a method to get userinputs. If I could get any help at all I would appreciate it. But please explain I really want to learn this rather then copy.
package Project2;
public class DiscountedLoan {
public DiscountedLoan(){
}
public void description(){
System.out.println("This program computes the proceeds of a discounted loan. Loan amount is in dollars and cents, Annual interest rate is in percentage, and the loan period is in number of years.");
}
}
There are a couple of object oriented principles you need to understand. The first is the idea of what a class is. A class is a thing. You have the definition, or the actual code, that represents the 'design' of the thing. It does stuff (methods) and has state (variables). An instance of a class is an actual implementation.
You can apply this principle to the real world easliy. For example, a car has a design somewhere. Engineers create models, CAD drawings etc and that is comparable to the coded class. At some point that design is turned into an actual car that is comparable to an instance of a class when your program runs.
In your code you have created a class definition for loan. It is just the design for what a loan looks like but doesn't actually contain any loan data. So when your program runs you need to create an instance of that loan to represent an actual loan. You can then use the methods of that class to populate the details, i.e. money, interest, etc.
When writing a method you need to decide a couple of things. What data does my method need to do its work and what data will it give back to me. In this case you may want to write a method that takes in a loan and returns a number to represent the discount. Your other method really just needs to display the user interface and call the appropriate methods with the right data.
This will allow you to read in integers that a user enters.
public int getLoanFromUserInput(){
try{
Scanner reader = new Scanner(System.in);
System.out.println("Enter a loan balance: ");
int n = reader.nextInt();
}catch(TypeMismatchException e){
System.out.println("Please enter a valid integer");
}
}

Understanding classes and variables in java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am new to Java and this was a example I found in the book I am reading.There are several things I do not understand in this code.Please help me to understand it.
/*
* CalculatorModel
* Encapsilates the data model used by the calculator Application
*/
public class CalculatorModel{
private double operand1;
private double operand2;
public void setOperand1(double value){
operand1=value;
}
public void setOperand2(double value){
operand2=value;
}
public double getOperand1(){
return operand1;
}
public double getOperand2(){
return operand2;
}
public String toString(){
String s = "operand 1=" + operand1 + "operand 2=" + operand2;
return s;
}
}
/*
* CalculatorHelper
* A class that performs mathematical functions for a calculator program
*/
public class CalculatorHelper{
private CalculatorModel calcModel;
public CalculatorHelper(){
calcModel=new CalculatorModel();
}
public void setOperand1(double value){
calcModel.setOperand1(value);
}
public void setOperand2(double value){
calcModel.setOperand2(value);
}
public double add(){
return calcModel.getOperand1()+calcModel.getOperand2();
}
public double subtract(){
return calcModel.getOperand1()-calcModel.getOperand2();
}
public double multiply(){
return calcModel.getOperand1()*calcModel.getOperand2();
}
public double divide(){
return calcModel.getOperand1()/calcModel.getOperand2();
}
}
Please help me to understand what is done by
private CalculatorModel calcModel;
public CalculatorHelper(){
calcModel=new CalculatorModel();
}
in the calculatorHelper class. Is calcModel a variable a variable of type CalculatorModel? What is the difference of having a object as a data type than a primitive data type to a variable?
If calcModel is a variable what is done by the line calcModel=new CalculatorModel();
I don't understand why it is important to have two classes as CalculatorModel and CalculatorHelper.
What is done with the method
public void setOperand1(double value){
calcModel.setOperand1(value);
}
in the helper class as there's already a setmethod in CalculatorModel class.
This is what I tried and what's wrong with this code?
public class Calculator{
private double num1,num2;
public void setValue1(double value1){
num1=value1;
}
public void setValue2(double value2){
num2=value2;
}
public double getValue1(){
return num1;
}
public double getValue2(){
return num2;
}
public double add(){
return getValue1()+getValue2();
}
public double subtract(){
return getValue1()-getValue2();
}
public double multiply(){
return getValue1()*getValue2();
}
public double divide(){
return getValue1()/getValue2();
}
}
"What is the difference of having a object as a data type than a primitive data type to a variable?"
Programming is all about data. Classes you can consider as complex data, and primitives as simple data. Say you have a class School
public class School {
}
What does school have? It has students. You can't represent a student with an of primitive types, because it just doesn't make sense for a student to be a double, int boolean, etc. So a student is another complex data type, like a school. So in order for the student to be represented as data contained by the school, you need a Student class also, which can hold the student's name, address and such
public class Student{
String firstName;
String lastName;
String address;
int age;
So to fully represent the student being in the school you use the has-a relationship, where School has-a Student
public class School {
Student student;
}
To delve even deeper, does a school only have one student? No, it should have many students. So you would represent that as a School having an array of Students
public class School {
Student[] students;
}
So in terms of data, you have a data tree like this now
School
Student
firstName
lastName
address
age
Student
firstName
lastName
address
age
This is the basic idea behind Object Oriented Programming. It's a lot easier to comprehend when you look at objects as actual physical objects. It makes it easier to understand the relationships.
Yes, your assumption that calcModel is a variable object of type CalculatorModel is right. when you say calcModel = new CalcModel(); it is actually creating another object in memory for storing the data that is to be stored(both operands) and storing the address of that object in calcModel. This way you can refer to object you created earlier. If you have worked with c earlier you can easily say calcModel is a pointer where as the object created is the data in the address located in the pointer.
The difference between a primitive type variable and object type variable is that the actual data that is to be stored in the variable is much more complex. For example the class CalculatorModel is a combination of two doubles... You can carry both operands as one entity by combining them(encapsulating) in a class. An object may also contain methods that can do some operations on the data stored in its member variables.
It is not necessary to have two classes, some people like it that way. I'm positively sure there is no need to create two classes in this case. Both can be merged as you have obviously did. Mind you there are no right and wrong ways to code, some ways of doing it are more preferable because they are more popular and avoids readability issues in long run. setOperand1() method is just using calcModel.setOperand1() so I don't see a necessity to have it done that way, calcModel.setOperand1 can be called directly from where ever setOperand1() is called. However, there can be case where you want to hide which function of setOperand1 is to be called or some complex operations are to be performed before calling calcModel.setOperand1. In such cases where you want to reduce burden for the callers of calcModel.setOperand1 by created setOperand1().
There is nothing wrong with the code. However you don't have to use getValue1() & getValue2() function in your add, subtract and other mathematical operations. you can simply say return num1+num2 Because, num1 & num2 are member variables of the same class.
private CalculatorModel calcModel;
public CalculatorHelper(){
calcModel=new CalculatorModel();
}
in the calculatorHelper class. Is calcModel a variable a variable of
type CalculatorModel ?What is the difference of having a object as a
data type than a primitive data type to a variable? If calcModel is a
variable what is done by the line calcModel=new CalculatorModel();
The variable calcModel is an instance of CalculatorModel, but is a class variable to the class CalculatorHelper. If you want to know about primitive data type vs object data type, check this article out. This line calcModel=new CalculatorModel(); is initializing the variable. You must do this in order to actually use the methods. Read more here.
I don't understand why it is important to have two classes as
CalculatorModel and CalculatorHelper.
There are cases where helper classes/methods are useful when it comes to separating large chunks of logic. Check this article out.
public void setOperand1(double value){
calcModel.setOperand1(value);
}
in the helper class as there's already a setmethod in CalculatorModel
class.
Yes, and it's calling that same exact set method but from the CalculatorHelper class.
This is what I tried and what's wrong with this code?
There seems to be nothing wrong with the code. I'm assuming you're using it properly from the main method (or whatever method you're using the class in).
This is essentially a Delegate Pattern by which the author has implemented the Calculator.
The Calculator serves the abstraction of the real-life Calculator.
By providing the helper/delegate class , I separate the behavior of the object.I am free to write my own implementation of add / subtract using a helper class. Calculator will serve as the Model of your calculations.
Consider this , If you try to modify the behavior you need to change the whole Calculator class and distribute it to the Client. However , I don't have to modify the Calculator but only the Helper which the client does/might not ship.
There is nothing wrong in what you have done - but consider this - what if you want to have Single instance of the Calculator - you can control instantion using helper class (in this case)
private CalculatorModel calcModel;
public CalculatorHelper(){
calcModel=new CalculatorModel();
}
is composition which is used here to separate concerns. The CalculatorHelper's concern is to know how to do addition, substraction, .. while the CalculatorModel knows the values, how to provide them to the outside and how to store them.
CalculatorHelperhas therefore an instance ofCalculatorModel` to which it can delegate all the things it does not know about. E.g.
public void setOperand1(double value){
calcModel.setOperand1(value);
}
The overall design is still questionable. First of all is it a bad encapsulation of a "calculator" because none of math operation reflect back to the model in any way. There needs to be a third class (CalculatorHelperHelper?) that knows how to deal with more than two operands.
It is also questionable whether or not a CalculatorModel should have two values at once. Two separate value objects would IMO make a lot more sense and would result in more modular code that would also be easier to understand as composition of objects.
The last point in this example is that encapsulating "storage" of values into CalculatorModel does not provide any real benefit here. It would if there was some kind of database backend or otherwise "complicated" logic that does not belong into CalculatorHelper. I would have taken more or less your approach in a simple real world scenario. Your code is not wrong. It's just a different approach.
The code in the context of the book and given that it is an example to show some design techniques is ok for that purpose. I would just do it very much different if I was to write a calculator. OO design is on the other hand not right or wrong and people can argue a lot about what good design is.

Error Cannot be applied to given types

Code:
public void checkHitDiscount(WineCase wineCase1)
{
if(hits%10==0)
{
wineCase1.setPrice()=0.9*wineCase1.getPrice;
System.out.println("Congratulations! You qualify for 10% discount.");
} else
System.out.println("You do not qualify for discount.");
}
The error I get here is:
Method setPrice cannot be applied to given types. required double,
found no argument.
I am trying to get a price field in the WineCase class modified. It is a double.
setPrice() is a method. You seem to also have a method called getPrice(), and these both probably corresponded to an instance variable called price within your object.
If price is private, then you call getPrice() as such:
wineCase1.getPrice();
This returns a double (assuming price is of type double).
And again, if price is private, then you'll need to set it as such:
wineCase1.setPrice(somePrice);
So in you're above example, if you want to set price to 90% of what it's currently at, the proper syntax would look like this:
wineCase1.setPrice(0.9*wineCase1.getPrice());
Alternatively, you could potentially write a public method for this class that looks like this:
public void discountBy(double disc) {
price *= 1.0 - disc;
}
// or like this:
public void discountTo(double disc) {
price *= disc;
}
// or both...
To use this method and apply a 10% discount to wineCase1, you'd do this:
wineCase1.discountBy(0.1);
// or like this:
wineCase1.discountTo(0.9);
Then you'll still use:
wineCase1.getPrice();
To retrieve the private variable, price, from the object.
And finally, this might potentially be the best solution, add these methods:
public double getPriceDiscountedBy(double disc) {
return price*(1.0-disc);
}
public double getPriceDiscountedTo(double disc) {
return price*disc;
}
These methods will allow you to retrieve the value of the discounted price without changing the original price of the item. These would be called in the same place you'd get a getPrice, but take a discount argument to modify only the returned price. For example:
double discountedPriceOutsideOfObject = wineCase1.getPriceDiscountedTo(0.9);
//or like this:
double discountedPriceOutsideOfObject = wineCase1.getPriceDiscountedBy(0.1);
If price field is double type then you simply do like below.
public void checkHitDiscount(WineCase wineCase1)
{
if(hits%10==0)
{
wineCase1.setPrice(0.9*wineCase1.getPrice());
System.out.println("Congratulations! You qualify for 10% discount.");
} else
System.out.println("You do not qualify for discount.");
}
And in WineCase.java the setPrice must be like below.
pubilc void setPrice(double price) {
this.price = price;
}
You cannot assign any value to methods, but method can return values.

How to choose your getters and setters in java

I have the payment class with only one local private variable - totalCost, as such totalCost also has a getter and setter methods. TotalCost is the only local variable because its the only one used in more than one method in the payment class. Should this class have more getters and setters?
public class Payment {
private int totalCost;
public Payment(){
}
public int calculateItemcost(int itemQuantity, int itemPrice){
return itemPrice * itemQuantity;
public int calculateTotalcost(int itemCost){
return totalCost = totalCost + itemCost;
}
public int calculateBalance(int clickedValue, int totalCost){
return this.totalCost = totalCost - clickedValue;
public int getTotalcost(){
return this.totalCost;
}
public void setTotalcost(int totalcost) {
this.totalCost = totalcost;
}
}
You use getters for the fields that you might need to "get" in other classes,
and setters for the fields that you might need to "set" in other classes. So before writing a getter/setter, think of your requirements.
Since you only have one field, which you already have getters and setters for. There is no point. Looks fine.
Although, refactor this:
public int calculateTotalcost(int itemCost){
return totalCost = totalCost + itemCost;
}
public int calculateBalance(int clickedValue, int totalCost){
return this.totalCost = totalCost - clickedValue;
}
To call the setter. Example:
public int calculateTotalcost(int itemCost){
setTotalCost(totalCost + itemCost);
return getTotalCost();
}
This way changes to totalCost is localized to the setTotalCost method.
Do you know the law of Demeter?
It gathers some small guidelines to avoid loose coupling in your code.
Getters and setters are the elements leading to thight coupling between classes.
Why?
Because getters and setters informs you about the implementation of a class (its field especially) and its design.
Developer who ALWAYS code with creation of getters/setters systematically have misunderstood totally the notion of Object-Oriented programming.
Indeed, this leads to anemic domain model.
Thus, it forces client to implements the business logic themselves even though it isn't its role.
To put in a nutshell: In an application, 80% of getters and setters are unnecessary.
Object-Oriented programming is about messages. You want a behaviour from an object, tell it ! Don't ask for information about its state in order to make your kitchen aside cause that would be typically a procedural way of coding.
(Tell ! Don't Ask !!) and favor the non-respect of DRY (Don't repeat yourself).
Two guidelines I follow.
First, not necessarily all private data should be exposed via getters and setters, since some of them may be for internal use only.
Second, the getters and setters should provide an object view, not an implementation view.
For example, if your class has a hard-coded 10% tax rate on purchases (forgetting for now that hard-coding this is a bad idea), you could have a getter for the taxation component even though it's a calculated value rather than a private member. In addition, you may want to set the value based on the pre-tax price.
So, if the pre-tax value has 10% added on for the government vultures, something like:
public void setPreTax (int preTaxAmt) {
totalCost = preTaxAmt * 11 / 10;
}
public int getTax (void) {
return totalCost / 11;
}
I haven't bothered using floating point for the calculations since it's irrelevant to the discussion and you're already using int.
This object/implementation split is a good thing - you should design your API based on the information you want to provide to the clients of it, not based on internal details.

Categories