练习题一
编写步骤:
定义接口A,普通类B实现接口A。
A接口中,定义抽象方法showA。
A接口中,定义私有方法show10(String str),循环打印10次str。
A接口中,定义默认方法showB10,showC10,分别调用show10方法,传入参数。
测试类中,创建B对象,调用showA方法,showB10方法,showC10方法
代码实现:
接口A:
public interface A
{
public abstract void showA();
public default void showB(){
System.out.println("BBBB");
}
}
普通类B:
public class B implements A
{
@Override
public void showA()
{
System.out.println("AAAAA");
}
}
测试类:
public class Test
{
public static void main(String[] args)
{
B b = new B();
b.showA();
b.showB();
}
}
测试结果截图:
练习题二:
代码实现:
Universe接口:
public interface Universe
{
public abstract void doAnything();
}
普通类Star:
public class Star
{
public void shine(){
System.out.println("star:星星一闪一闪亮晶晶");
}
}
普通类Sun:
public class Sun extends Star implements Universe
{
@Override
public void doAnything()
{
System.out.println("sun:太阳吸引着9大行星旋转");
}
@Override
public void shine()
{
System.out.println("sun:光照八分钟,到达地球");
}
}
测试类:
public class Test
{
public static void main(String[] args)
{
Star s = new Star();
s.shine();
System.out.println("================");
Universe u = new Sun();
u.doAnything();
Sun s1 =(Sun) u;
s1.shine();
}
}
测试结果截图:
简易电脑模拟
具体代码实现:
USB接口:
public interface USB
{
//开启
void open();
//关闭
void close();
}
鼠标类(Mouse):
public class Mouse implements USB
{
@Override
public void open()
{
System.out.println("鼠标开启");
}
@Override
public void close()
{
System.out.println("鼠标关闭");
}
//鼠标点击方法
public void click(){
System.out.println("鼠标点击");
}
}
键盘类(KeyBoard):
public class KeyBoard implements USB
{
@Override
public void open()
{
System.out.println("键盘开启");
}
@Override
public void close()
{
System.out.println("键盘关闭");
}
public void type(){
System.out.println("键盘打印");
}
}
电脑类(Computer):
public class Computer
{
public void run(){
System.out.println("电脑启动");
}
public void shutDown(){
System.out.println("电脑关机");
}
public void useUsb(USB usb){
if(usb!=null){
usb.open();
//进行类型转换
if(usb instanceof Mouse){
Mouse mouse = (Mouse)usb;
mouse.click();
}else if (usb instanceof KeyBoard){
KeyBoard keyBoard = (KeyBoard)usb;
keyBoard.type();
}
usb.close();
}
}
}
测试类(Test):
public class Test
{
public static void main(String[] args)
{
Computer computer = new Computer();
computer.run();
USB m =new Mouse();
USB k =new KeyBoard();
computer.useUsb(m);
computer.useUsb(k);
computer.shutDown();
}
}
结果截图: