java中把参数类型改成接口

本文探讨了在Java中如何通过将参数类型更改为接口来提升代码的可重用性。作者引用Allen Holub的观点,强调通过接口而非类继承实现多态,以增强方法的通用性。举例说明将Rectangle类参数改为Rectangular接口后,方法能处理更多类型的对象。此外,还展示了如何在方法中直接使用接口参数调用方法,实现了不同类对象的多态性调用,进一步证明了接口参数的优势。
摘要由CSDN通过智能技术生成

java中把参数类型改成接口

1.正如Allen Holub在《Build User Interfaces for Object-Oriented Systems》中所指出的,在面向对象编程中,代码重用真正的要点在于通过接口参数类型利用多态性,而不是通过类继承:
“……我们通过对接口而不是对类编程达到代码重用的目的。如果某个方法的所有参数都是对一些已知接口的引用,那么这个方法就能够操作这样一些对象:当我们编写方法的代码时,这些对象的类甚至还不存在。从技术上说,可重用的是方法,而不是传递给方法的对象。”
在“措施一”得到的结果上应用Holub的看法,当某块代码能够编写为独立的全局过程时,只要把它所有类形式的参数改为接口形式,我们就可以进一步提高它的可重用能力。经过这个改动之后,过程的参数可以是实现了该接口的所有类的对象,而不仅仅是原来的类所创建的对象。由此,过程将能够对可能存在的大量的对象类型进行操作。
例如,假设有这样一个全局静态方法:
static public boolean contains(Rectangle rect, int x, int y) {……}

这个方法用于检查指定的点是否包含在矩形里面。在这个例子中,rect参数的类型可以从Rectangle类改变为接口类型,如下所示:
static public boolean contains(Rectangular rect, int x, int y) {……}

而Rectangular接口的定义是:
public interface Rectangular {Rectangle getBounds();}

现在,所有可以描述为矩形的类(即,实现了Rectangular接口的类)所创建的对象都可以作为提供给pRectangular.contains()的rect参数。通过放宽参数类型的限制,我们使方法具有更好的可重用性。

2.接口作为参数的方法的使用

方法内直接用接口形参调用方法


public class InterfaceText {
	public void say(InterfaceA f) {
		System.out.println(f.method());
	}
	public static void main(String[] args) {
		InterfaceA f = new ClassA(2);   //对象的多态,向上转型
		InterfaceText t = new InterfaceText();
		t.say(f);
		InterfaceA x = new ClassB(2);
		t.say(x);
	}
}

interface InterfaceA {            //自定义InterfaceA接口
	abstract int method();
}

class ClassA implements InterfaceA {   //自定义ClassA类实现Interface接口,并重写method方法
	private int n;

	ClassA(int n) {
		this.n = n;
	}

	public int method() {      //重写方法
		int sum = 0;
		for (int i = 1; i < n + 1; i++) {
			sum += i;
		}
		return sum;
	}
}
class ClassB implements InterfaceA {  // 自定义ClassB类实现InterfaceA接口并重写method方法
	private int n;

	ClassB(int n) {
		this.n = n;
	}

	public int method() {     //重写方法
		int product = 1;
		for (int i = 1; i < n + 1; i++) {
			product *= i;
		}
		return product;
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值