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");
    	}
    }
    
  • 相关阅读:
    3305: Hero In Maze II (优先队列+bfs)
    2016年5月8日 GDCPC省赛总结
    POJ 2361 Tic Tac Toe
    about 字节
    KMP模式匹配
    scau 8616 汽车拉力比赛
    海盗分金--大于半数才成立
    scau 10692 XYM-入门之道
    函数模板和类模板成员函数的定义通常放在头文件中
    c语言运算符优先级巧记
  • 原文地址:https://www.cnblogs.com/liubing2018/p/8426072.html
Copyright © 2011-2022 走看看