抽象类的特点:
1.抽象类不能被实例化 (即不能用new去产生对象)
2.抽象函数必须被重写,除非子类也是抽象类
(抽象类中 函数只需要声明,无需实现(无方法体),所以必须要重写)
3.在抽象类中可以含着普通成员函数
接口的定义:
Interface 接口名{
方法声明;
}
例如:interface Demo{
void fun(); //方法声明,无方法体。在使用实现接口时,要重写此函数
}
接口中定义成员变量是全局静态变量 默认用public static final 标识
例如
class math
{
public final double PI=3.14; //如果不用final 或 static 会报错
}
接口可以继承另一个接口 通过implements 多个接口继承格式:
class 子类 extends 父类 implemtents 接口1,接口2,……{}
接口的实现运用例子
定义一个接口,里面包含值为3.14的常量PI和抽象方法double area()。
例如:
Interface A{ //定义接口
Double area(); //接口定义函数无实现
}
定义接口B,里面包含抽象方法void setColor(String c)。
例如:
Interface B{ //定义接口
void setColor(String c);//接口定义函数无实现
}
定义接口C,该接口继承了接口A和B,里面包含抽象方法void volume()。
例如:
class C extends A,B{ //一个接口可继承多个接口
void volume();
}
定义圆柱体类Cylinder实现接口C,该类中包含三个成员变量:底圆半径radius、
圆柱体的高height、颜色color。
class Cylinder implements C { //定义一个类实现接口
float radius,height;
String color;
Cylinder(float radius,float height,String color) //有参构造函数
{
this.radius=radius;
this.height=height;
this.color=color;
}
public void setColor(String c) //接口方法的重写
{
System.out.println(this.color);
}
public double area()//接口方法的重写
{
return PI*radius*radius;
}
public void volume()//接口方法的重写
{
System.out.println(PI*radius*radius*height);
}
}
创建主类来测试类Cylinder。
public class Main {
public static void main(String[] args)
{
Cylinder C= new Cylinder(5,5,"red");//调用有参构造函数并传参过去
System.out.println(C.area());
C.volume();
C.setColor("blue");
}
}
扩展例子:父类和子类对象类型转换
interface Compute { //接口
int computer(int n,int m);
}
class add implements Compute { //加功能,接口的实现
public int computer(int n,int m)
{
return n+m;
}
}
public class divide implements Compute { //除功能,接口的实现
public int computer(int n,int m)
{
return n/m;
}
}
public class multiply implements Compute{ //乘功能,接口的实现
public int computer(int n,int m)
{
return n*m;
}
}
class subtract implements Compute{//减功能,接口的实现
public int computer(int n,int m)
{
return n-m;
}
}
public class UseCompute
{
public static void useCom(Compute com, int one, int two) {
//参数:定义了一个接口类型的 变量 ,所以在主函数中调用时也要传如接口类型的实参
System.out.println(com.computer(one, two));
}
}
public class Test {
public static void main(String[] args)
{
Compute Use=new add(); //因为add()也是接口类型,所以可以赋值给接口类型的Use
UseCompute.useCom(Use, 8, 2);
//这样使用时useCom 必须提前分配空间(即在UseCompute 内将useCom定义为静态,否则报错 )
//**************************************//另一种写法 常规写法
UseCompute Use=new UseCompute(); //创建对象
Use.useCom(new add(),8,2); //实参直接分配内存给Compute com相当Compute Use=new add();
//***************************************
Use = new subtract();
UseCompute.useCom(Use, 16, 2);
Use = new divide();
UseCompute.useCom(Use, 16, 2);
Use = new multiply();
UseCompute.useCom(Use, 16, 2);
}
}