- 论坛徽章:
- 0
|
java interface的一个经典实例
![]()
import java.io.*;
interface CAR
{
void start();
void stop();
}
class SmallCar implements CAR
{
public void start()
{
System.out.println("smallcar start...");
}
public void stop()
{
System.out.println("smallcar stop!");
}
}
class BigCar implements CAR
{
public void start()
{
System.out.println("bigcar start...");
}
public void stop()
{
System.out.println("bigcar stop!");
}
}
class TestCar
{
public void operCar(CAR c)
{
c.start();
c.stop();
}
}
public class TestInterface
{
public static void main(String[] args)
{
TestCar tc=new TestCar();
SmallCar sc=new SmallCar();
BigCar bc = new BigCar();
tc.operCar(sc);
tc.operCar(bc);
}
}
类似C++中的纯虚函数,接口就是给出一些空的方法,到具体用的时候再由使用该接口的方法自己定义内容
要注意的是,想用接口必须实现接口的所有方法.
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/40671/showart_392617.html |
|