我读了很多关于“接口(interface)”和“抽象类”的帖子
基本上,当我们谈论对象的特性时,我们使用“抽象类”。
当我们谈论对象能够做什么时,我们使用“接口(interface)”。
但这仍然令人困惑,所以我自己做一个例子来练习。
所以现在我在想一个对象' cargo ;
public abstract class cargo {
protected int id;
public abstract int getWidth(int width);
public abstract int setWidth(int width);
public abstract int setHeight(int h);
public abstract int getHeight(int h);
public abstract int setDepth(int d);
public abstract int getDepth(int d);
public abstract int volume(int w,int h,int d);
public int getId(){
return this.id;
}
public abstract int setId();
public abstract void setBrand();
public abstract void getBrand( );
.....so on , still have a lot of characteristic of a cargo
}
//in the other class
public class usaCargo extends cargo{
....
private
}
所以这里有几个关于我的设计的问题。
1.那么在真实的编程项目世界中,我们真的是像上面那样做吗?对我来说,我认为这是好的设计,我们符合 cargo 的基本特征。
public interface registration{
public void lastWarrantyCheck();
}
不过好像不适合这里...
我试图在 OOP 上获得更多意义。原谅我长长的问题。
最佳答案
您将在 Abstract 类中定义变量,以便在抽象类中定义的方法具有要使用的变量。这些变量的范围取决于您希望具体类如何访问这些变量:private
当您想强制具体类通过抽象类中定义的 getter 或 setter 时应该使用。protected
当您想要让具体类直接访问变量时应该使用。public
当您希望任何类都可以访问该变量时,应使用该变量。
Cargo 对象可能实现的合理接口(interface)可以是 Shippable ,就像如何将 cargo 从源移动到目的地一样。有些 cargo 可以通过 cargo 列车运输,有些可以通过飞机运输,等等。实现 Shippable 并定义如何运输这种类型的 cargo 取决于具体的类。
public interface Shippable {
public void ship();
}
最后,在接口(interface)中定义的变量必须是 public static 和 final 意味着它将是一个常量变量。
希望这可以为您解决问题!
关于oop - 在面向对象编程中,我们什么时候需要抽象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15036900/