java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > java隐藏与重写

Java 继承后成员的隐藏与重写(示例详解)

作者:我命由我12345

在Java中,继承是一种允许新类(子类)继承另一个类(父类)的成员(包括字段、方法等)的特性,本文给大家介绍了Java 继承后成员的隐藏与重写,感兴趣的朋友跟随小编一起看看吧

Java 继承后成员的隐藏与重写

1、子类没有定义成员

  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");
    }
}
  1. CommonStore.java
public class CommonStore extends BaseCommonStore {
}
  1. 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、子类定义同名成员

  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");
    }
}
  1. 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");
    }
}
  1. 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隐藏与重写内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文