多态:

1、三个条件:继承,重写,向上转型(父类引用指向子类对象);

2、优点:扩展性好,多元化发展;

3、作用:父类里面的方法被重写之后,不能在多态里面调用

先了解下继承:

1、子类的构造的过程中必须调用其基类的构造方法。

2、子类可以在自己的构造方法中使用superArgument_list)调用基类的构造方法。

   a、使用this(agument list)调用本类另外的构造方法

   b、如果用super,必须写在方法的第一句

3、如果子类的构造方法中没有显式地调用基类构造方法,则系统默认调用基类无参数的构造方法。

   a、如果子类构造方法中既没有显式调用基类构造方法,而基类中又没有无参的构造方法,则编译出错。

Egpackage xzp;

publicclass A {

protectedvoid print(String s){

System.out.println(s);

    }

    A(){

print("A()");

    }

publicvoid f(){

print("A:f()");

    }

staticclass B extends A{

 B(){

 print("B()");

}

publicvoid f(){

 print("B:f()");

   }

publicstaticvoid main(String[] args) {

B b=new B();

b.f();

}

}

}

结果:A()

B()

B:f()

再了解方法的重写(OverRide)

A、在子类中可以根据需要对从基类中继承来的方法进行重写。

B、重写方法必须和被重写方法具体有相同的方法名称参数列表和返回类型。

C、重写方法不能使用必被重写方法更严格的访问权限。

举例:

package xzp;

publicclass FatherClass {

publicintvalue;

publicvoid f(){

value=100;

System.out.println("FatherClass.value="+value);

}

}

class ChildClass extends FatherClass{

publicintvalue;

publicvoid f(){

value=200;

   System.out.println("ChildClass.value="+value);

   System.out.println(value);

   System.out.println(super.value);

   }

publicstaticvoid main(String[] args) {

ChildClass c=new ChildClass();

c.f();

}

}

运行结果:ChildClass.value=200

200

0

代码修改为:

package xzp;

publicclass FatherClass {

publicintvalue;

publicvoid f(){

value=100;

System.out.println("FatherClass.value="+value);

}

}

class ChildClass extends FatherClass{

publicintvalue;

publicvoid f(){

super.f();

value=200;

   System.out.println("ChildClass.value="+value);

   System.out.println(value);

   System.out.println(super.value);

   }

publicstaticvoid main(String[] args) {

ChildClass c=new ChildClass();

c.f();

}

}

 运行结果:

FatherClass.value=100

ChildClass.value=200

200

100

最后了解下向上转型:父类的引用指向子类的对象;

举例子(1)没有向上转型的时候代码:

package xzp;

publicclass B {

publicvoid fun(){

}

}

class C extends B{

publicvoid fun(int a,int b){

     int sum;

     sum=a+b;

System.out.println(sum);

}

publicstaticvoid main(String[] args) {

C c=new C();

c.fun(1,2);

}

}

结果:3

2)向上转型的时候代码:

package xzp;

publicclass B {

publicvoid fun(){

System.out.println(1);

}

}

class C extends B{

publicvoid fun(int a,int b){

int sum;

sum=a+b;

System.out.println(sum);

}

publicstaticvoid main(String[] args) {

B c=new C();

c.fun();

}

}

运行结果为:1

总结:只要满足上面三种情况即为多态。