定义:
多态是继数据抽象和继承之后的又一特征,多态可以改善代码的结构与可读性还可创建可扩展的程序。
举例说明:
人类有“吃”的动作,人还分为“男人”,“女人”但是男人和女人的吃的动作是不相同的。
普通方法:
public class Test {
public Test() {}
public void eat(String type) {
if (type.equals("man")) {
System.out.println("man eat----");
}
if (type.equals("woman")) {
System.out.println("woman eat----");
}
}
}
public static void main(String[] args) {
Test test=new Test();
test.eat("man");
}
输出结果:man eat—-
引用多态:
/**
* 基类
*
* @author 蒙
*
*/
public class People {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void eat() {
System.out.println("People类eat方法输出----" + this.getName());
}
public void sleep() {
System.out.println("People类sleep方法输出----" + this.getName());
}
}
/**
* 子类
*
* @author 蒙
*
*/
public class Woman extends People {
@Override
public void eat() {
System.out.println("Woman类eat方法输出----" + super.getName());// 输出当前name值
}
}
/**
* 子类
* @author 蒙
*
*/
public class Man extends People{
@Override
public void eat(){
System.out.println("Man类eat方法输出----" + this.getName());// 输出当前name值
}
}
public static void main(String[] args) {
People p=new Woman();//创建子类,传递给测试方法
p.setName("woman子类");
whoEat(p);
}
输出结果:**Woman类eat方法输出—-woman子类
People类sleep方法输出—-woman子类**
总结:如果使用普通方法实现,会有如下缺点如果新增一个“child”的“吃”就要去修改eat方法(eat原始代码),如果使用多态无论新增多少个类型的“吃”,只要继承people类重写eat方法就可以实现(无需修改原始eat)。
成员变量说明:
/**
* 基类
*
* @author 蒙
*
*/
public class People {
private String name="people";
public int i=100;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void eat() {
System.out.println("People类eat方法输出----" + this.getName());
}
}
/**
* 子类
*
* @author 蒙
*
*/
public class Woman extends People {
private String name="woman";
public int i=10;
@Override
public void eat() {
System.out.println("Woman类eat方法输出----" + this.getName());// 输出当前name值
System.out.println("Woman类eat方法输出----" + super.getName());// 输出父类name值
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static void main(String[] args) {
People people=new Woman();//创建子类,传递给测试方法
people.setName("woman子类");
whoEat(people);
System.out.println(people.getName());
System.out.println(people.i);
}
输出结果:
Woman类eat方法输出—-woman子类
Woman类eat方法输出—-people
woman子类
100
解释:
people.setName(“woman子类”);调用的是woman(子类)类的set方法,
System.out.println(people.getName()); 输出调用woman(子类)的get方法,
System.out.println(people.i);输出people(父类)的成员变量
总结:
父类与子类具有相同的成员变量,多态下访问的是父类的成员变量
父类与子类具有相同的方法(就是子类重写父类方法),多态下访问的是子类的方法
注意:静态方法不存在被重写的概念,表面上看似重写,实质static的方法不能被重写,