接口
C++:
纯虚函数为了说明该类是抽象类
没法让抽象类里面不产生任何纯虚函数
但是JAVA有对应的方法(abstract)
class People{
};
class CanWeigh { //解决称重代码复用问题在
public:
int weight;
int getWeight() const {
return weight;
}
}
class Stu : public People,public CanWeigh {
public:
int getWeight() const{ //重点(constd的使用)
return 50;
}
};
class Car:public Canweigh {
public:
int getWeight() {
return 1000;
}
};
void fun(const Stu &x){ //称重函数
cout<<"Charge:"<<x.getWeight()*10<<endl;
}
void fun(const Car &x) {
cout<<"Charge:"<<x.getWeight()*10<<endl;
}
//以上两个fun发生了拷贝代码的现象,因为可以称重的物体太多了
//不同的对象都有称重这个问题
//这种跨类的需求在java中用接口来实现
void fun(const Canweigh &x)
{
cout<<"Charge:"<<x.getWeight()*10<<endl;
}
//体现了C++中多继承有必要的地方
int main() {
Stu zs;
Car a;
fun();
return 0;
}
Java 接口(interface)
public interface Canweight{ //语法和类一样 加了public需要在它自己的文件中定义 bu不加只能在当前的文件中使用
}
interface的地位等于一个 abastract class
interface Canweight{ //语法和类一样 加了public需要在它自己的文件中定义 bu不加只能在当前的文件中使用
int getWeight(){//提示报错说抽象方法没有body 所以默认这就是抽象方法
return 10;
}
}
class Car implements Canweigh{//Car实现了接口CanWeigh
}
public interface Canweigh {
public int k;
private double d;//报错 不可以用private修饰
int wei=123//相当与static final int wei = 123;
static int getWeight() {
return 10;
}
}
interface可以看成可以被多继承的特殊的抽象类
使用方法:
class test {
public static void hehe(CanWeigh w){
cout<<"Weight:"<<w.wei<<endl;
}
public static void main(Strin argv[])
{
Stu zs = new Stu();
Tea ls = new Tea();
hehe(zs);
hehe(ls);
}
}