day10--多态中成员的访问特点
This commit is contained in:
@@ -2,7 +2,14 @@ package com.inmind.poly08;
|
|||||||
|
|
||||||
public class Animal {
|
public class Animal {
|
||||||
|
|
||||||
|
int numFu = 1;
|
||||||
|
int num = 2;
|
||||||
|
|
||||||
public void run(){
|
public void run(){
|
||||||
System.out.println("动物跑");
|
System.out.println("动物跑");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void getNumFu(){
|
||||||
|
System.out.println(numFu);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,14 @@
|
|||||||
package com.inmind.poly08;
|
package com.inmind.poly08;
|
||||||
|
|
||||||
public class Cat extends Animal{
|
public class Cat extends Animal{
|
||||||
|
int numZi = 3;
|
||||||
|
int num = 4;
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
System.out.println("猫闪着跑,闪身步");
|
System.out.println("猫闪着跑,闪身步");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void getNumZi(){
|
||||||
|
System.out.println(numZi);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,13 @@ package com.inmind.poly08;
|
|||||||
继承或者实现【二选一】
|
继承或者实现【二选一】
|
||||||
方法的重写【意义体现:不重写,无意义】
|
方法的重写【意义体现:不重写,无意义】
|
||||||
父类引用指向子类对象【格式体现】
|
父类引用指向子类对象【格式体现】
|
||||||
|
--------------------------------------------------
|
||||||
|
多态中成员变量和成员方法的访问特点
|
||||||
|
在多态中的成员变量的访问特点:
|
||||||
|
1.通过对象直接访问成员变量,对象创建时,=左边是谁,就优先使用谁的成员变量,如果没有向上找
|
||||||
|
2.通过对象调用成员方法,间接操作成员变量,方法属于谁,就优先使用谁的方法,如果没有向上找
|
||||||
|
|
||||||
|
编译看左边,运行看右边!!!!
|
||||||
*/
|
*/
|
||||||
public class Demo08 {
|
public class Demo08 {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
@@ -18,5 +25,14 @@ public class Demo08 {
|
|||||||
|
|
||||||
animal1.run();
|
animal1.run();
|
||||||
animal2.run();
|
animal2.run();
|
||||||
|
//访问animal2的属性
|
||||||
|
System.out.println(animal2.num);
|
||||||
|
System.out.println(animal2.numFu);
|
||||||
|
//System.out.println(animal2.numZi);//在多态中子类的属性无法访问
|
||||||
|
//访问animal2的行为
|
||||||
|
animal2.getNumFu();//编译看左边,运行看右边
|
||||||
|
//编译看左边,左边是Animal类,类中没有getNumZi,并且Animal的父类也没有getNumZi方法,所以编译不通过
|
||||||
|
//animal2.getNumZi();
|
||||||
|
animal2.run();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user