I am aware of the distinction between tight coupling and loose coupling, according to this articles: https://www.upgrad.com/blog/loose-coupling-vs-tight-coupling-in-java/
What I do not understand is the examples it uses.
For loose coupling, the Java code:
class Volume {
public static void main(String args[]) {
Cylinder b = new Cylinder(25, 25, 25);
System.out.println(b.getVolume());
}
}
final class Cylinder {
private int volume;
Cylinder(int length, int width, int height) {
this.volume = length * width * height;
}
public int getVolume() {
return volume;
}
}
For tight coupling, the Java code:
class Volume {
public static void main(String args[]) {
Cylinder b = new Cylinder(15, 15, 15);
System.out.println(b.volume);
}}
class Cylinder {
public int volume;
Cylinder(int length, int width, int height) {
this.volume = length * width * height; }}
Can anyone please explain how does the second code make the two classes (Volume and Cylinder) bound together (tightly coupled)? Or what makes the first code loosely coupled? Thanks.
Generally, in OOP you want to declare your class properties as
privateso you can encapsulate them. Doing this, you don't directly have access to them and you cannot change them by mistake. This is intended for code maintenance reasons, and it is especially useful when you have multiple developers that have access to the codebase, as you create a barrier between important class properties and the next developer.This thing creates 2 problems though:
getVolume()method comes into play here. This method is called a getter and is solely created to get the value of its related property by returning the property - not directly by accessing it.setVolume(value)method (which is not present in your code) comes into play here. This method is called a setter and is solely created to change the value of its related property through a parameter - again, not directly.