Encapsulation and loose coupling are largely abstract ideas, which is to say that their might not be exact meanings as you put it. So with subtle cases, it can often come down to opinion. However, here is the jist of it...
Encapsulation.
Encapsulation just means protecting (encapsulating) class members that should not be accessible (or do not need to be accessible) from the outside of the class. It allows you to define exactly how that variable/method should be interacted with. For example;
class A{
private int a;
public void setA(int a){
this.a = a;
}
}
class B{
public int b;
}
In class A
, the a
variable is encapsulated. You can only set a
from outside this object instance through the defined method which allows us to define exactly how it can be allowed to be set. It also means you can not retrieve the value of a
because we have not defined a method to allow it.
In class B
in contrast, b
is public and anyone from outside the class can do whatever they want with it. Which, is not very well encapsulated. Think of Encapsulation as having members surrounded by a protective capsule, which makes sure that members are only interacted with in a good-predefined way.
Links:
Loose Coupling
Coupling refers to the degree that two classes are bound to each other, or have knowledge of the workings of each other. If two concrete classes could not work without the existence of the other class they are considered tightly coupled. Loose coupling is probably more of an abstract concept than Encapsulation, but they do relate to each other. If, for example, a class' variables are not encapsulated, then any class that uses it is said to be tightly coupled with it if it uses those variables.
class A{
public int a;
}
class B{
public static void main(String[] arg){
A ay = new A();
ay.a = 7;
}
}
In the above example classes A
and B
are tightly coupled, because B
has in depth knowledge of the variable states of A
and could not run if class A
did not exist.
The wiki says the following on Loose coupling;
Strong coupling occurs when a dependent class contains a pointer
directly to a concrete class which provides the required behavior. The
dependency cannot be substituted, or its "signature" changed, without
requiring a change to the dependent class. Loose coupling occurs when
the dependent class contains a pointer only to an interface, which can
then be implemented by one or many concrete classes.
Links: