您的位置:首页 > 编程语言 > Java开发

java笔记--day09--多态(一)

2016-08-25 22:06 141 查看
1 多态概述

某一个事物,在不同时刻表现出来的不同状态

2 多态的前提和体现

有继承关系

有方法重写

有父类引用指向子类对象: 父 f = new 子();

3 多态中的成员访问特点:

A:成员变量

编译看左边,运行看左边。

B:构造方法

创建子类对象的时候,访问父类的构造方法,对父类的数据进行初始化。(这其实是因为继承的原因)

C:成员方法

编译看左边,运行看右边。

D:静态方法

编译看左边,运行看左边。

(静态和类相关,算不上重写,所以,访问还是左边的)

由于成员方法存在方法重写,所以它运行看右边。

PolymorphicDemo:

class Fu{
int num1;
public Fu(){
num1 = 10;
}

public void show1(){
System.out.println("num1 is " + num1);
}
public static void show3(){
System.out.println("static function in Fu class");
}

}

class Zi extends Fu{
int num1 = 11;
int num2 = 20;
public Zi(){}
public void show1(){
System.out.println("num1 is " + num1);
}
public void show2(){
System.out.println("num2 is " + num2);
}
public static void show3(){
System.out.println("static function in Zi class");
}
}

class PolymorphicDemo2{
public static void main(String[] args) {
Fu f = new Zi();
System.out.println("num1 is " + f.num1); //member variable
//System.out.println("num2 is " + f.num2); //This line must be commented out,or there is a fail during compilation.(error:can not find the symbol)

f.show1();
//f.show2();//This line must be commented out,or there is a fail during compilation.(error:can not find the symbol)
f.show3();//static member method
}
}

/*
running result:
num1 is 10
num1 is 11
static function in Fu class
*/


4 总结

从running result可以看出:

num1 is 10 //表示了多态中成员变量访问的特点;以及多态中new一个子类对象的时候,其实也对父类的构造方法进行了初始化(因为Zi继承了Fu)。

num1 is 11 //表示了多态中成员方法访问的特点

static function in Fu class //表示对于静态方法,其实没有重写这一概念
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: