编辑器我选择的是Notepad++,学习视频:毕向东Java基础教程
// 继承和多态的基本运用,包含成员变量、成员函数和静态函数的情况
class Person
{
int age = 24; //成员变量
static String name = "person";
void work() //成员函数
{
System.out.println("Person has work!");
}
static void method() //静态函数
{
System.out.println("Person name: "+name);
}
}
class Student extends Person
{
int age = 26;
static String name = "student";
static int xuehao = 100101;
void work()
{
System.out.println("Student has work!");
}
static void method()
{
System.out.println("Student name: "+name+"; Student xuehao: "+xuehao);
}
}
class MulType
{
public static void main(String[] args)
{
Person p = new Student(); //多态
System.out.println("p.age: "+p.age);
p.work();
p.method();
Student s = new Student();
System.out.println("s.age: "+s.age);
s.work();
s.method();
}
}
知识点:多态中的成员变量、成员函数和静态函数的调用:
(1)成员变量
- 编译时,参考引用型变量所属的类中是否有调用的成员变量,有,编译通过,否,失败
- 运行时,参考引用型变量所属的类中是否有调用的成员变量,并运行该所属类中的成员变量
- 编译和运行都参考等号左边,成员变量没有覆盖,(父/子类)谁调用就执行谁的成员变量
(2)成员函数(非静态)
- 编译时,参考引用型变量所属的类中是否有调用的成员函数,有,编译通过,否,失败
- 运行时,参考对象所属的类中是否有调用的成员函数
- 编译看左边,运行看右边。
- 非静态成员函数,依赖于对象,需要动态的绑定到指定的对象上。
(3)静态函数
- 编译时,参考引用型变量所属的类中是否有调用的静态函数,有,编译通过,否,失败
- 运行时,参考引用型变量所属的类中是否有调用的静态函数,并运行该所属类中的静态函数
- 编译和运行都看左边
- 静态函数可通过类名来调用,无需创建对象,(父/子类)谁调用就执行谁的静态函数