安全向下转移--instanceof
格式:对象 instanceof 类名称
package zhuanxing; public class main { public static void main(String[] args) { animal1 animal1=new dog(); animal1.eat(); if (animal1 instanceof dog1){ dog1 dog1 =(zhuanxing.dog1)animal1; dog1.eat1(); } if (animal1 instanceof dog){ dog dog=(zhuanxing.dog)animal1; dog.eat2(); } } }
练习:笔记本调用usb接口类
接口
package benjiben; public interface USB { public abstract void open(); public abstract void off(); }
鼠标类
package benjiben; import java.util.Scanner; public class mouse implements USB{ @Override public void open() { System.out.println("打开鼠标成功"); } @Override public void off() { System.out.println("关闭鼠标成功"); } public void click(){ Scanner sc=new Scanner(System.in); System.out.println("鼠标正在点击"); int a=sc.nextInt(); System.out.println("鼠标点击了"+a+"下!"); } }
键盘类
package benjiben; import java.util.Scanner; public class keyboard implements USB{ @Override public void open() { System.out.println("打开键盘成功"); } @Override public void off() { System.out.println("关闭键盘成功"); } public void input(){ Scanner scanner=new Scanner(System.in); System.out.println("请在键盘输入"); String a=scanner.next(); int zm=0; int sz=0; int qt=0; {char[] chars = a.toCharArray(); for (int i = 0; i < chars.length; i++) { char dg =chars[i]; if ('A'<=dg && dg<='z'){ zm++;} else if ('0'<=dg && dg<='9'){ sz++; }else { qt++; } } System.out.println("键盘输入了:"+a); System.out.println("其中字母有:"+zm+"个"); System.out.println("数字有"+sz+"个"); System.out.println("其他有"+qt+"个");} }}
笔记本了类
package benjiben; public class computer { public void Poweron(){ System.out.println("电脑开机!"); } public void Poweroff(){ System.out.println("电脑关机!"); } public void use(USB usb){ usb.open(); if (usb instanceof mouse){ mouse mouse=(benjiben.mouse)usb; mouse.click(); }else if (usb instanceof keyboard){ keyboard keyboard=(benjiben.keyboard)usb; keyboard.input(); } usb.off(); } }
主方法
package benjiben; public class diannao { public static void main(String[] args) { computer computer=new computer();//创建电脑 computer.Poweron();//电脑开机 USB usb= new mouse();//准备鼠标 computer.use(usb);//电脑使用鼠标 keyboard keyboard=new keyboard();//准备键盘 computer.use(keyboard);//电脑使用键盘 computer.Poweroff();//电脑关机 } }