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;
    	}
    }

  • 相关阅读:
    菜根谭#77
    菜根谭#76
    菜根谭#75
    菜根谭#74
    菜根谭#73
    python迭代器
    python爬取网页数据
    yii2验证规则
    python装饰器的理解
    php中多图上传采用数组差集处理(array_diff,array_map)
  • 原文地址:https://www.cnblogs.com/wjchang/p/3671714.html
Copyright © 2011-2022 走看看