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

  • 相关阅读:
    maven插件安装与使用
    java面试题
    关于java的GC
    技术人员要树立自己的品牌
    为什么IT公司都应该鼓励开源
    你应该坚持写博客 即使没有读者
    计算机基础
    收藏 | 产品经理不可不知的 7 种技术思维
    我讨厌你公事公办的样子
    子序列问题【LIS、LCS、LCIS】
  • 原文地址:https://www.cnblogs.com/wjchang/p/3671714.html
Copyright © 2011-2022 走看看