Java Interface接口的简单应用

本文介绍了一种通过接口实现输出方法的灵活替换机制,详细解释了如何定义接口和类之间的关系,以及如何在外部动态插入实现代码。通过简单的示例,展示了接口在编程实践中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

比如现在有个类:

package com.inter;

public class MyClass {
	
	public void output() {
		//show something...
	}
	
}

不同的需求下 output() 需要输出不同的信息,要如何在外部将特定的实现代码插入到 output() 中?接下来我们定义一个接口:

package com.inter;

public class MyClass {
	private MyInterface mInterface;
	
	public interface MyInterface {
		//The abstract method in the interface
		public void show();
		
	}
	
	public void output() {
		//Call the method of interface
		mInterface.show();
	}
	
	public void setInterface(MyInterface mInterface) {
		this.mInterface = mInterface;
		
	}
	
}

现在来实现接口:

package com.inter;

public class Main  {

	public static void main(String[] args) {
		MyClass mc = new MyClass();
		mc.setInterface(new MyClass.MyInterface() {

			@Override
			public void show() {
				System.out.println("This is my first interface!");
				
			}
			
		});
		mc.output();
	}

}


这是接口的简单应用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值