zoukankan      html  css  js  c++  java
  • java多态-向上转型和向下转型

    向上转型:符合“is a”,是安全的,子类向上到父类,多余的属性和方法会丢弃

    向下转型:不安全的,用instanceof提前判断一下,以免抛出异常

    instanceof用法:

      result = object instanceof class

      result:布尔类型

      object:必选项,任意对象表达式

      class:必选项,任意已定义的对象类

      说明: 如果object是class或者其子类的一个实例,则instanceof运算符返回true,如果不是或者object是null,则返回false

    public class AnimalDemo {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Animal animal1 = new Dog("旺财");//向上转型
    		Animal animal2 = new Cat("招财猫");
    		animal1.eat();
    		//animal1.sleep();因为向上转型,所以子类的sleep()丢弃了
    		//父类的引用变量只能调用父类中有的方法,或者是子类重写父类的方法
    		animal2.eat();
    		//向下转型不安全,需要提前用instanceof判断一下,防止异常抛出
    		if(animal2 instanceof Cat){
    			System.out.println("111");
    			Cat cat = (Cat)animal2;
    			cat.sleep();
    		}
    		
    	}
    
    }
    
    class Animal{
    	private String name;
    	public Animal(String name) {
    		this.name = name;
    	}
    	public void eat() {//子类要重写
    		System.out.println(name);
    	}
    }
    class Dog extends Animal{
    	public Dog(String name) {
    		super(name);
    	}
    	public void eat() {
    		System.out.println("吃狗粮");
    	}
    	public void sleep() {
    		System.out.println("sleep");
    	}
    }
    class Cat extends Animal{
    	public Cat(String name) {
    		super(name);
    	}
    	public void eat() {
    		System.out.println("吃猫粮");
    	}
    	public void sleep() {
    		System.out.println("sleep");
    	}
    }
    
  • 相关阅读:
    读入优化
    poj 3216 Repairing Company
    poj 2594 Treasure Exploration
    poj 1419 Graph Coloring
    POJ 3308 Paratroopers(最小点权覆盖)(对数乘转加)
    bzoj2007: [Noi2010]海拔
    bzoj4552: [Tjoi2016&Heoi2016]排序
    bzoj1041: [HAOI2008]圆上的整点
    oracle 的服务器进程(PMON, SMON,CKPT,DBWn,LGWR,ARCn)
    undo表空间居高不下和enq: US
  • 原文地址:https://www.cnblogs.com/liubing2018/p/8426072.html
Copyright © 2011-2022 走看看