I know there is a difference due to research but I can only find similarities between them... I was hoping if someone would clarify the difference and if you can an example for each would really help. Java program please also would this program count as encapsulation or information hiding or even both
class DogsinHouse {
private int dogs;
public int getdog() {
return dogs;
}
public void setdog(int amountOfDogsNow) {
dogs = amountOfDogsNow;
}
}
The code portion you post is an example of both. Encapsulation is the technique for which a Java class has a state (informations stored in the object) and a behaviour (the operations that the object can perform, or rather the methods). When you call a method, defined in a class A, in a class B, you are using that method without knowing its implementation, just using a public interface.
Information Hiding it's the principle for which the istance variables are declared as private (or protected): it provides a stable interface and protects the program from errors (as a variable modification from a code portion that shouldn't have access to the above-mentioned variable).
Basically:
Encapsulation using information hiding:
public class Person {
private String name;
private int age;
public Person() {
// ...
}
//getters and setters
}
Encapsulation without information hiding:
public class Person {
public String name;
public int age;
public Person() {
// ...
}
//getters and setters
}
In the OOP it's a good practice to use both encapsulation and information hiding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With