多态分为1.引用的多态2.方法的多态
1.引用的多态
又分为两种:1.父类引用指向本类的对象2.父类引用指向子类的对象(同C++)
2.方法的多态
指向子类时用的是子类的重载方法,如果该子类没有重载该方法,则还是用父类的方法,要注意的是如果引用是父类的,那么不能使用父类中没有的方法
具体使用方法类似于C++,比如父类为交通方式,属性为名字,载客量,载客方式,子类则为具体化的交通方式,代码如下
//父类
public class Transportation {
private int capacity;
private String way;
private String name;
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
public String getWay() {
return way;
}
public void setWay(String way) {
this.way = way;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void transport(){
System.out.println(name+" can take "+capacity+" people "+way);
}
}
//子类代表
public class Bus extends Transportation{
Bus(){
setCapacity(30);
setName("Bus");
setWay("on the road");
}
}
//测试类
public class Initial {
public static void main(String[] args) {
// TODO Auto-generated method stub
Transportation demo[]=new Transportation[3];
demo[0]=new Bus(); //注意!虽然上面new了一次,但这里仍然要new
//因为指向的是新的内存空间,如果没有会提示
//Bus中没有定义该函数
demo[1]=new Ship();
demo[2]=new Airplane();
for(int i=0;i<3;i++){
demo[i].transport();
}
}
}
主要的点就在于父类数组的定义Transportation demo[]=new Transportation[3];
demo[0]=new Bus();
向上隐式转换,向下强制转换(大-》小,父->子)
强制转换有风险,比如代码
Animal animal=new Dog();
Dog dog2=(Dog)animal;//ok, animal is the reference of Dog
Cat cat=(Cat)animal;//ok to run but error, because animal is a //Dog but not Cat
如果运行以上代码(不完整),虽然编译器不会报错,但是结果还是错的,因为类型不相同,所以在进行强制转换之前我们可以先使用 instanceof判断,比如animal instanceof Cat
,返回false则不进行强制转换。
instanceof通过返回一个布尔值来指出,这个对象是否是这个特定类或者是它的子类的一个实例。如果 object 是 class 的一个实例,则 instanceof 运算符返回 true。如果 object 不是指定类的一个实例,或者 object 是 null,则返回 false。
if(animal instanceof Cat){
Cat cat=(Cat)animal;
}
else{
System.out.println("Cannot cast");
}
在上面的例子中,animal这个object并不是Cat的实例,而是Dog的,所以返回false
抽象类:类似C++,关键字abstract定义抽象类和抽象方法。(public abstract class xx)
抽象类定义方法只需声明不需实现,抽象类可以没有抽象方法,抽象类不能直接创建,可以定义引用变量
抽象方法没有具体实现就直接以;结束
注意抽象类里的抽象方法也需要abstract
接口:关键字interface,implements
接口内部都是由常量和抽象的方法组成,不关心具体的实现,java是单继承的语言,接口可以间接地实现多继承。
定义语法:
//定义在IPlayGame中(接口名前面有个大写的i)
【修饰符】 interface 接口名 [ extends 父接口1,父接口2... ]{
抽象方法;
常量;
}//extends外的中括号表明括号里面的接口是可选的。
使用的语法:
public class 【类名】 extends 【父类】 implements 接口1,接口2...{
//实现
//如果要继承父类,则父类一定要在接口前面,implements
//IPlayGame extends Telphone 是错的
}