JAVA SE 接口实现与Comparable接口

接口实现

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();
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

起名字可真难QAQ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值