多态--强转--多态方法返回值类型

package duotai;

public class Animal {
int age;

public void eat() {
System.out.println("吃饭");
}

public void sleep() {
System.out.println("睡觉");
}
}

----------狗狗类--------

package duotai;

public class Dog extends Animal {

@Override
public void eat() {
System.out.println("吃肉");

}

public void guard() {
System.out.println("狗狗看门");
}

}

---------猫类---------

package duotai;

public class Cat extends Animal {

}

------------多态-----------------

package duotai;

/*
* 多态
*/
public class Test01 {
public static void main(String[] args) {
Dog dog = new Dog();
// 父类引用指向子类对象
Animal a = new Dog();
a.eat();
a.sleep();
}
}

-------------强制类型转换--------两个类之间必须要有继承关系-----------

package duotai;

/*
* 强制类型转换
*两个类之间必须要有继承关系
*/
public class Test02 {
public static void main(String[] args) {
Animal a = new Dog();
// 因为Animal中没有guard方法,所以不能直接调用
// 想要调用子类特有的方法的时候,需要进行强制类型转换
// 从大类型转向小类型的时候也叫作向下转型
Dog dog = (Dog) a;

dog.guard();
// 编译没有问题,但是在运行的时候会报出ClassCastException
// 类转型错误
// 可以通过instanceof关键字判断当前对象是否属于一个类型
// a-->桌子上的水果 Cat--->相当于你心中的苹果
if (a instanceof Dog) {
Dog dog2 = (Dog) a;
System.out.println("一样");
} else {
System.out.println("不一样");
}
if (a instanceof Cat) {
Cat cat = (Cat) a;
System.out.println("一样");
} else {
System.out.println("不一样");
}
}
}

--------------使用多态作为方法的返回值类型--------------

package duotai;

/*
* 使用多态作为方法的返回值类型
*/
public class Test03 {
public static void main(String[] args) {
Animal animal = getname(0);
animal.eat();
if (animal instanceof Dog) {
Dog dog = (Dog) animal;
dog.guard();
}
}

// 根据传入的数据来判断创建哪个动物的对象
// 通用
private static Animal getname(int i) {
if (i == 0) {
return new Dog();
} else {
return new Cat();
}

}
}

猜你喜欢

转载自www.cnblogs.com/Koma-vv/p/9561544.html