对象的参数传递实例
1、打开电脑上的eclipse软件,配置好jdk的

2、点击左上角的file,点击new,点击Javaproject。

3、新建一个class文件,自己取名字,勾引main选项,自动调用main方法

4、method(new Cat());
method(new Dog());
}
//Cat c = new Dog();狗是一只猫,这是错误的
/*public static void method(Cat c) {
c.eat();
}
public static void method(Dog d) {
d.eat();
}*/
//如果把狗强转成猫就会出现类型转换异常,ClassCastException
public static void method(Animal a) { //当作参数的时候用多态最好,因为扩展性强
//关键字 instanceof 判断前边的引用是否是后边的数据类型
if (a instanceof Cat) {
Cat c = (Cat)a;
c.eat();
c.catchMouse();
}else if (a instanceof Dog) {
Dog d = (Dog)a;
d.eat();
d.lookHome();
}else {
a.eat();
}
}
}
class Animal {
public void eat() {
System.out.println("动物吃饭");
}
}
class Cat extends Animal {
public void eat() {
System.out.println("猫吃鱼");
}
public void catchMouse() {
System.out.println("抓老鼠");
}
}
class Dog extends Animal {
public void eat() {
System.out.println("狗吃肉");
}
public void lookHome() {
System.out.println("看家");
}
}

5、控制台会出现
猫吃鱼
抓老鼠
狗吃肉
看家
