我知道紧耦合和松耦合之间的区别,根据本文:https://www.upgrad.com/blog/loose-coupling-vs-tight-coupling-in-java/
我不明白的是它所用的例子。
对于松散耦合,Java代码:
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;
}
}对于紧密耦合,Java代码:
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; }}谁能解释一下第二个代码是如何使这两个类(卷和圆柱)结合在一起(紧密耦合)的?或者是什么使第一段代码松耦合?谢谢。
发布于 2022-01-30 17:02:59
通常,在OOP中,您希望将类属性声明为private,以便封装属性。这样做,您就不能直接访问它们,也不能错误地更改它们。这是出于代码维护的原因,当您有多个可以访问代码基的开发人员时,它尤其有用,因为您在重要的类属性和下一个开发人员之间创建了一个屏障。
不过,这件事造成了两个问题:
getVolume()方法在这里起作用。此方法称为getter,仅通过返回属性(而不是直接访问it.setVolume(value)方法(在代码中不存在)将在这里起作用。此方法称为setter,仅用于通过参数更改其相关属性的值,而不是直接。。
发布于 2022-07-06 03:18:01
我认为这是紧密耦合代码中的一个简单原因,您可能会遇到这样的缺点:您过于依赖卷变量。例如,如果将引用字段从卷更改为另一个,则还必须在调用函数中更改它。
https://stackoverflow.com/questions/70916609
复制相似问题