面向对象进阶-多态

什么是多态:同种类型的对象表现出的不同形态。

多态的表现形式:

父类类型 对象名称=子类对象;

多态的前提:

  • 有继承/实现关系

  • 有父类引用指向子类对象

  • 有方法重写

package oop.polymorphism.a01polymorphismdemo01;

public class Person {
    String name;
    int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    public void show(){
        System.out.println(name+","+age);
    }
}
package oop.polymorphism.a01polymorphismdemo01;

public class Student extends Person{
    @Override
    public void show(){
        System.out.println("学生信息为:"+getName()+","+getAge());
    }
}
package oop.polymorphism.a01polymorphismdemo01;

public class Teacher extends Person{
    @Override
    public void show(){
        System.out.println("老师信息为:"+getName()+","+getAge());
    }
}
package oop.polymorphism.a01polymorphismdemo01;

public class Administractor extends Person{
    @Override
    public void show(){
        System.out.println("管理员信息为:"+getName()+","+getAge());
    }
}
package oop.polymorphism.a01polymorphismdemo01;

public class Test {
    public static void main(String[] args) {
      Student s=new Student();
      s.setName("karry");
      s.setAge(24);
      Teacher t=new Teacher();
      t.setName("王见过");
      t.setAge(38);
      Administractor a=new Administractor();
      a.setName("管理员");
      a.setAge(35);
      register(s);
      register(t);
      register(a);
    }
    public static void register(Person p){
        p.show();
    }
}

多态调用成员的特点

  • 变量调用:编译看左边,运行也看左边

  • 方法调用:编译看左边,运行看右边

你可能感兴趣的:(java,servlet,android)