接口实现
package chap;
interface PCI {
void start();
void stop();
}
class SoundCard implements PCI{
public void start() {
System.out.println("Du..du");
}
public void stop() {
System.out.println("Sound stop!");
}
}
class NetworkCard implements PCI{
public void start() {
System.out.println("Send...");
}
public void stop() {
System.out.println("Network stop!");
}
}
class MainBoard//通过这个方法,主板上可以插入任何符合PCI插槽规范的卡,实际上是调用两个抽象方法的总方法
{
public void usePCICard(PCI/*此处要写接口类型,因为是对接口中两个抽象方法的调用*/ p) {
p.start();
p.stop();
}
}
public class PCITest {
public static void main(String[] args) {
MainBoard mb = new MainBoard();
//在主板上插入网卡
NetworkCard nc = new NetworkCard(); //NetworkCard 可以用PCI替换
mb.usePCICard(nc);
//在主板上插入声卡
SoundCard sc = new SoundCard();
mb.usePCICard(sc);
}
}
利用Comparable接口,根据特定属性排序。
package chap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Student implements Comparable<Student>{
String name;
double height;
public Student(String name, double height) {
this.name = name;
this.height = height;
}
public int compareTo(Student other) {
/*
compareTo与Comparable对应,均不能随意更改
*/
return (int)((other.height - this.height) * 100);
/*
这里只能是int类型,乘100是为了保证作差后是有效的整数。
(other.height - this.height) -> 对应降序
(this.height - other.height) -> 对应升序
*/
}
}
class Class{
String name;
public Class(String name) {
this.name = name;
}
List<Student> students = new ArrayList<>();
public void addStudent(Student student) {
students.add(student);
}
public void sortStudents() {
Collections.sort(students);
}
/*
若实现Comparable接口,则可直接利用Collections.sort()进行排序。
*/
public void showStudents() {
for(int i=0; i<students.size(); i++) {
Student temp = (Student)(students.get(i));
System.out.println(this.name + " " + temp.name + " " + temp.height);
}
}
}
public class StudentTest {
public static void main(String...strings) {
Class class1 = new Class("计算机18");
class1.addStudent(new Student("张三", 1.6));
class1.addStudent(new Student("王五", 1.81));
class1.addStudent(new Student("李四", 1.61));
class1.sortStudents();
class1.showStudents();
}
}