Java中继承为单继承,只有一个父类
接口
public interface 类名{
public void foo();
//接口里全是没有实现的方法,只有声明,不允许有实现,只能抽象方法
//不需要加抽象关键字
}
特性
- 接口不能被实例化
- 实现类必须实现接口的所有方法
- 实现类可以实现多个接口
- 接口中的变量是静态常量
定义usb接口
public interface UsbInterface {
/**
* USB接口提供服务。
*/
void service();
}
实现接口
public class UDisk implements UsbInterface {
public void service() {
System.out.println("连接USB口,开始传输数据。");
}
}
使用接口
UsbInterface uDisk = new UDisk();
uDisk.service();
接口中只有两种东西
1.常量
2.方法声明
实例
某软件公司,需要2个能编程的“人”开发一个刚接到的项目
//编程接口
public interface IProgram {
public void program();
}
public class Person {
}
//程序员
public class Programmer extends Person implements IProgram {
@Override
public void program() {
System.out.println("我编编编");
}
}
//机器人类
public class Robot implements IProgram{
@Override
public void program() {
System.out.println("我编编编,但是我不累");
}
}
//软件公司类
public class SoftwareCommany {
public static void main(String[] args) {
//需要2个能编程的“人”开发一个刚接到的项目
IProgram[] iPrograms = new IProgram[2];//数组里放得是2个能编程的“人”
iPrograms[0] = new Robot();
iPrograms[1] = new Programmer();//只要是实现了接口的类,都可以看成是接口类型
for(int i = 0; i < iPrograms.length; i++)
{
iPrograms[i].program();//让他们编程序
}
}
}
一个更复杂的实例
public interface MyCompareable {
public int CompareTo(Object obj);
}
一个汽车类实现了MyCompareable 接口
public class Car implements MyCompareable{
int id;
String name;
@Override
public String toString() {
return "Car{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
public Car(int id, String name) {
this.id = id;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public int CompareTo(Object obj) {
Car car = (Car)obj;
return this.id - car.id;
}
}
排序类
public class BubbleSort {
public static void endSort(Car[] arr2) {
System.out.println("原序列");
System.out.println(Arrays.toString(arr2));
//两次for循环解决
for(int i = 0; i < arr2.length-1; i++){
for(int j=0; j < arr2.length-1-i;j++){
if(arr2[j].CompareTo(arr2[j+1])>0){
Car temp = arr2[j];
arr2[j] = arr2[j+1];
arr2[j+1] = temp;
}
}
}
System.out.println();
System.out.println("两层循环排序");
System.out.println(Arrays.toString(arr2));
}
}
主方法
public class Main {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Car[] cars = new Car[3];
cars[0] = new Car(11,"baima");
cars[1] = new Car(15,"benci");
cars[2] = new Car(13,"audi");
BubbleSort.endSort(cars);
}
}
网友评论