Java-面向对象_向下转型_向上转型
pig类:
public class Pig extends Animal{ public void shut() { System.out.println("我是小猪,我会嗯嗯嗯叫"); } }
Animal类:
public class Animal { public void shut(){ System.out.println("我是小动物,我会叫"); } }
测试类:
public class Test { public static void main(String[] args) { Girl g = new Girl(); Pig pig = new Pig(); Animal animal = pig;//转型:向上转型 // g.play(animal); //加入转型的代码: //将Animal转为pig类型; Pig pig2 = (Pig)animal;//转型:向下转型 pig2.shut(); } }
思考之前的equals方法
public boolean equals(Object obj) {//Object obj = new Phone(); /* * instanceof运算符: * a instanceof b: * 判断a对象是否是b这个类的实例,如果是 返回true 如果不是返回false */ if(obj instanceof Phone) { //要把obj的类型转换为当前类的类型 Phone other = (Phone)obj; //this指的是当前调用 if(this.getName()==other.getName()&&this.getPrice()==other.getPrice()&&this.getYear()==other.getYear()) { return true; } } return false; }