Java 继承后成员的隐藏与重写(示例详解)
作者:我命由我12345
在Java中,继承是一种允许新类(子类)继承另一个类(父类)的成员(包括字段、方法等)的特性,本文给大家介绍了Java 继承后成员的隐藏与重写,感兴趣的朋友跟随小编一起看看吧
Java 继承后成员的隐藏与重写
1、子类没有定义成员
- BaseCommonStore.java
public class BaseCommonStore {
public static final String TAG = "TAG:" + BaseCommonStore.class.getSimpleName();
public static void sayHello() {
System.out.println(TAG + " sayHello");
}
public String tag = "tag:" + BaseCommonStore.class.getSimpleName();
public void sayOk() {
System.out.println(tag + " sayOk");
}
}- CommonStore.java
public class CommonStore extends BaseCommonStore {
}
- test
System.out.println(CommonStore.TAG); CommonStore.sayHello(); CommonStore commonStore = new CommonStore(); System.out.println(commonStore.tag); commonStore.sayOk();
# 输出结果 TAG:BaseCommonStore TAG:BaseCommonStore sayHello tag:BaseCommonStore tag:BaseCommonStore sayOk
2、子类定义同名成员
- BaseCommonStore.java
public class BaseCommonStore {
public static final String TAG = "TAG:" + BaseCommonStore.class.getSimpleName();
public static void sayHello() {
System.out.println(TAG + " sayHello");
}
public String tag = "tag:" + BaseCommonStore.class.getSimpleName();
public void sayOk() {
System.out.println(tag + " sayOk");
}
}- CommonStore.java
public class CommonStore extends BaseCommonStore {
public static final String TAG = "TAG:" + CommonStore.class.getSimpleName();
public static void sayHello() {
System.out.println(TAG + " sayHello");
}
public String tag = "tag:" + CommonStore.class.getSimpleName();
public void sayOk() {
System.out.println(tag + " sayOk");
}
}- test
System.out.println(CommonStore.TAG); CommonStore.sayHello(); CommonStore commonStore = new CommonStore(); System.out.println(commonStore.tag); commonStore.sayOk();
# 输出结果 TAG:CommonStore TAG:CommonStore sayHello tag:CommonStore tag:CommonStore sayOk
小结
| 成员 | 示例 1 | 示例 2 |
|---|---|---|
| 静态变量 | 继承父类 | 隐藏父类 |
| 静态方法 | 继承父类 | 隐藏父类 |
| 实例变量 | 继承父类 | 隐藏父类 |
| 实例方法 | 继承父类 | 重写父类 |
到此这篇关于Java 继承后成员的隐藏与重写(示例详解)的文章就介绍到这了,更多相关java隐藏与重写内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
