多态性(Polymorphism):一个东西,在不同的情况下,呈现出不同的行为
两类:
静态多态性:函数重载
void add(int a,int b){}
void add(int a,int b,int c){}
调用:
add(1,2); add(3,4,5);
动态多态性:在面向对象中,父类引用可以指向子类对象
性质:
(1)父类引用能够调用的函数都是子类中的函数
(2)子类中特有的函数对父类不可见
//在面向对象中,父类引用可以指向子类对象 class Dialog{ void fun1(){ System.out.println("Fun1"); } void show(){ System.out.println("父类show");} } class FontDialog extends Dialog{ void fun2(){ System.out.println("Fun2"); } void show(){ System.out.println("子类show");} } class Main{ public static void main (String[] args) { Dialog d = new FontDialog();//动态多态性的基础 d.fun1(); //d.fun2(); 报错 d.show(); }
作用:用于两个场合
(1)形参为父类类型,可以传入子类对象做实参
void fun(Dialog d){}
调用:
fun(new FontDialog());//也是对的
举例说明:二次开发
(2)返回类型为父类类型,实际上可以返回子类对象
Dialog fun(){
FontDialog fd=new FontDialog();
return fd;
}
class Window{ void clickMenu(Dialog d){ d.show(); } } class Dialog{ void show(){} } class FontDialog extends Dialog{ void show(){ System.out.println("字体对话框显示"); } } //----------------------------------------------- class MyFontDialog extends Dialog{ void show(){ System.out.println("漂亮对话框显示"); } } class Main{ public static void main (String[] args) { new Window().clickMenu(new MyFontDialog()); } }
抽象类——类似于C++中的虚基类
abstract class Dialog{ //抽象类
abstract void show();
}
性质:
(1)抽象类必须用abstract修饰
(2)抽象类中至少含有一个抽象函数
(3)抽象函数必须用abstract修饰,并且没有函数体
(4)抽象函数必须被子类重写,否则报错。除非子类也是抽象类
(5)抽象类不能被实例化,只能实例化其子类对象
abstract class Dialog{ //抽象类 abstract void show(); void fun(){System.out.println("adfadf");} } class FontDialog extends Dialog{ void show(){ System.out.println("字体对话框显示"); } } class Main{ public static void main (String[] args) { Dialog d = new FontDialog(); d.fun(); }
抽象类中可以有普通函数
Java中还有一种比抽象类还要抽象的“类”,叫做接口(Interface)
只允许有抽象函数,不能有普通函数。
interface Dialog{ //接口
void show(); //默认就是public抽象函数
}
class FontDialog implements Dialog{
public void show(){ System.out.println("字体对话框显示"); }
}
(1)接口用interface修饰
(2)接口中的函数默认为public抽象函数
(3)接口用implements实现,不用extends继承
(4)一个类可以同时实现多个接口,用逗号隔开,但是不可以同时继承多个抽象类
/抽象类中可以有普通函数,Java中还有一种比抽象类 //还要抽象的“类”,叫做接口(Interface), //只允许有抽象函数,不能有普通函数。 interface Dialog{ //接口 void show(); //默认就是public抽象函数 } class FontDialog implements Dialog{ public void show(){ System.out.println("字体对话框显示"); } } class Main{ public static void main (String[] args) { Dialog d = new FontDialog(); d.show(); }
如果我们继承多个接口的话呢,如果在继承的过程当中我们遇到了重名 的方法,我们便会遇到错误,这个时候我们便需要一些改动。
interface Dialog1{ //接口 int show(); //默认就是public抽象函数 void query(); } interface Dialog2{ //接口 void show(); //默认就是public抽象函数 } class FontDialog implements Dialog1,Dialog2{ public void show(){ } public int show(int s){ return s; } public void query(){} }