Data Hiding refers to the concept of hiding the inner workings of a class and simply providing an interface through which the outside world can interact with the class without knowing what’s going on inside.
The purpose is to implement classes in such a way that the instances (objects) of these classes should not be able to cause any unauthorized access or change in the original contents of a class. One class does not need to know anything about the underlying algorithms of another class. However, the two can still communicate. It can be implemented with the idea of Data Abstraction and Data Encapsulation.
Encapsulation is to make sure that "sensitive" data is hidden from users. To achieve this, you must:
declare class variables/attributes as private
provide public get and set methods to access and update the value of a private variable
You learned from the previous chapter that private variables can only be accessed within the same class (an outside class has no access to it). However, it is possible to access them if we provide public get and set methods.
The get method returns the variable value, and the set method sets the value.
Syntax for both is that they start with either get or set, followed by the name of the variable, with the first letter in upper case:
Example-1:
public class Person {
private String name; // private = restricted access
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}
In the above example, the get method returns the value of the variable name.
The set method takes a parameter (newName) and assigns it to the variable name. The this keyword is used to refer to the current object.
However, as the name variable is declared as private, we cannot access it from outside this class.
Instead, we use the getName() and setName() methods to access and update the variable.
Example-1a:
public class TestPerson {
public static void main(String[] args) {
Person myObj = new Person();
// Set the value of the name variable to "Awie"
myObj.setName("Awie");
System.out.println(myObj.getName());
}
}
The output will be:
Awie
Example-2:
public class Cars{
// Instance variable
private String make;
private int year;
private int speed;
// constructor method
public Cars(String m, int y){
make = m;
year = y;
speed = 0;
}
// other methods
public void setMake(String m){
make = m;
}
// this method will return the make
public String getMake(){
return make;
}
// this method will return the speed
public int getSpeed(){
return speed;
}
// this method will return the year
public int getYear(){
return year;
}
}
Example-2a:
public class TestCars3{
public static void main(String []args){
// Following statement would create an object myCar
Cars myCar = new Cars( "Iriz", 2016);
System.out.println(myCar.getMake);
System.out.println(myCar.getYear);
myCar.setMake("Jazz");
System.out.println("My new car is " + myCar.getMake);
}
}
Better control of class attributes and methods
Class attributes can be made read-only (if you only use the get method), or write-only (if you only use the set method)
Flexible: the programmer can change one part of the code without affecting other parts
Increased security of data
A class named PC2Circle is defined as follows.
Private instance variable named radius that represents the radius of the circle.
The constructor PC2Circle() initialized radius to 0.0.
setRadius(double) method that set a new radius value
getRadius() method that returns the radius
getArea() method that returns the area of the circle.
getCircumference() method that returns the circumference of the circle.
Write the code for PC2Circle class and a test program named TestPC2Circle that reads the input and prints the output as described below.
The first line contains an integer n which determines the number of test cases. Each of the following n lines contains a positive real number r which represents the radius of the circle.
For each test case, the output contains a line in the format "Case #x: ", where x is the case number (starting from 1) followed by the radius, area, and circumference of the circle. Format the output in 4 decimal places.
2
9.0
5.5
Case #1: 9.000 254.4690 56.5487
Case #2: 5.500 95.0332 34.5575
The following is the PC2Circle class.
public class PC2Circle {
// private instance variable
private double radius;
// constructor1-without parameter
public PC2Circle() {
radius = 0.0;
}
void setRadius(double rad) {
radius = rad;
}
double getRadius() {
return radius;
}
double getArea() {
return radius * radius * Math.PI;
}
double getCircumference() {
return 2 * Math.PI * radius;
}
}
The following is the TestPC2Circle class.
import java.util.Scanner;
import java.text.DecimalFormat;
public class TestPC2Circle {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("0.0000");
double radius, area, circumference;
int N = sc.nextInt();
for (int i = 1; i <= N; i++) {
PC2Circle myCircle = new PC2Circle();
radius = sc.nextDouble();
myCircle.setRadius(radius);
area = myCircle.getArea();
circumference = myCircle.getCircumference();
System.out.print("Case #" + i + ": "); System.out.print(df.format(myCircle.getRadius())+ " ");
System.out.print(df.format(area) + " ");
System.out.println(df.format(circumference));
}
}
}
Within a healthy, balanced diet, a man needs around 10,500kJ (2,500kcal) a day to maintain his weight. For a woman, that figure is around 8,400kJ (2,000kcal) a day. These values can vary depending on age, metabolism, and levels of physical activity, among other things. If you want to lose weight, it's helpful to calculate your BMR. Basal metabolic rate (BMR) is the total number of calories that your body needs to perform basic, life-sustaining functions. The following formula can be used to calculate your BMR.
· Men: BMR = 88.362 + (13.397 * weight in kg) + (4.799 * height in cm) - (5.677 * age in years)
· Women: BMR = 447.593 + (9.247 * weight in kg) + (3.098 * height in cm) - (4.330 * age in years)
However, your daily calories requirements (DCR) can vary depending on your lifestyle. A sedentary lifestyle (e.g. office desk work) would require less calories as compared to the calories required by an athlete.
DCR = activity_level * BMR
Activity level Description
1.2 Less exercise
1.375 1-3 times exercise weekly
1.55 4-5 times exercise weekly
1.725 6 times exercises weekly
1.9 Weight training / marathon
Write a program to calculate your DCR using the following specification. A class called MyBMR will have the following data:
Private instance variables named bmr that represent your BMR.
Constructor method MyBMR (double weight, double height, int age, int gender) that initialized your bmr. (Code for Gender: 1 for female and 2 for male)
Getter method:
getBMR() that returns your bmr.
getDCR(int num) : state your level of activity which is the amount of your exercise (0 – never, 1 – once a week, 2 – twice a week, and so on).
The UML Class Diagram for class MyBMR is as follows.
MyBMR
-bmr: double
+MyBMR (double weight, double height, int age, int gender)
+getBMR(): bmr
+getDCR(int num): void
Write the code for MyBMR class and a test program to test MyBMR class that reads the input and print the output as described below.
The input consists of a few test cases. For each test case, the first line of input is a positive integer n which indicates the number of test cases. Each of the following n lines contains 5 numbers representing the weight, height, age, gender, and level of activity.
For each test case, output a line in the format "Case #x:" where x is the case number (starting from 1), followed by the BMR and DCR value.
Note: Print BMR and DCR in two decimal places
4
84 152 47 1 3
50 154 23 2 0
60 156 20 1 4
73 157 43 1 6
Case #1: 1491.73 2051.12
Case #2: 1366.69 1640.02
Case #3: 1399.10 2168.61
Case #4: 1422.82 2454.36
Problem Description
A savings account enables you to save or deposit your money into an account and receive certain interest with no stated maturity. Available at all the banking institutions in Malaysia, interest earned on your balance is normally credited to your account every month. The minimum deposit to open a savings account varies from one banking institution to another and can be as low as RM1.
A savings account class called SavingAccount is defined as follows.
Private instance variable called balance represents the account balance.
The constructor SavingAccount(double amount)that sets the amount it receives as the initial value of the account balance.
addInterest() method that adds a 3% interest to the account balance.
getBalance() method that returns the account balance.
The UML Class Diagram for class Tv is as the following.
SavingAccount
balance:double
+SavingAccount(double amount)
+addInterest():void
+getBalance():double
Write the code for SavingAccount class and a test program to test SavingAccount class that reads the input and print the output as described below.
The input consists of a few test cases. For each test case, the first line of input is a positive integer n (1 ≤ n ≤ 20) which indicates the number test cases. Each of the following n lines contains a decimal points number represent the amount deposited (in Ringgit Malaysia) when opening a savings account.
For each test case, output a line in the format "Case #x:" where x is the case number (starting from 1), followed by the account balance, which is a number with decimal points that represents an amount in Ringgit Malaysia.
3
1.00
150.00
0
Case #1: 1.03
Case #2: 154.50
Case #3: 0.00