zoukankan      html  css  js  c++  java
  • java例程练习(对象转型及instanceof关键字)

    public class Test {
    	public static void main(String[] args) {
    		Animal a = new Animal("name");
    		Cat c = new Cat("Tom", "Blue");
    		Dog d = new Dog("Pipi", "Black");
    		
    		System.out.println(a instanceof Animal);
    		System.out.println(c instanceof Animal);
    		System.out.println(d instanceof Animal);
    		System.out.println(a instanceof Cat);
    		System.out.println();
    		
    		a = new Dog("Bangbang", "Yellow");
    		System.out.println(a instanceof Animal);
    		System.out.println(a instanceof Dog);
    		System.out.println();
    		
    		Dog d1 = (Dog)a;
    		System.out.println(d1 instanceof Animal);
    		System.out.println(d1 instanceof Dog);
    		System.out.println();
    		
    		Test test = new Test();
    		test.info(a);
    		test.info(c);
    		test.info(d);
    		test.info(d1);
    	}
    	
    	public void info(Animal	a) {
    		System.out.print("" + a.name);
    		if(a instanceof Cat) {
    			Cat cat = (Cat)a;
    			System.out.print(" has " + cat.eyeColor + " eyes");
    		} else if(a instanceof Dog) {
    			Dog dog = (Dog)a;
    			System.out.print(" has " + dog.furColor + " fur");
    		}
    		System.out.println();
    	}
    
    }
    
    class Animal {
    	public String name;
    	Animal(String name) {
    		this.name = name;
    	}
    }
    
    class Cat extends Animal {
    	public String eyeColor;
    	Cat(String n, String c) {
    		super(n);
    		eyeColor = c;
    	}
    }
    
    class Dog extends Animal {
    	public String furColor;
    	Dog(String n, String c) {
    		super(n);
    		furColor = c;
    	}
    }

  • 相关阅读:
    while 循环 。。
    数据运算,运算符
    字符串常用操作
    列表常用操作
    三级菜单
    杂七杂八
    简单的登陆程序001
    猜年龄游戏
    实现密文输入密码
    使用urllib2打开网页的三种方法
  • 原文地址:https://www.cnblogs.com/wjchang/p/3671714.html
Copyright © 2011-2022 走看看