• 技术文章 >java >java教程

    java中使用static的注意点

    小妮浅浅小妮浅浅2021-03-02 10:43:26原创5740

    在关键词的使用上,我们已经对static方法有所了解,为了防止在使用时出现一些不必要的错误,了解它的使用范围是每个人都要掌握的。本篇把static的使用注意点分为两个方面,一个是访问的范围,另一个是有关方法调用的注意,下面我们一起来看看完整的static使用注意点吧。

    1、使用static方法的时候,只能访问static声明的属性和方法,而非static声明的属性和方法是不能访问的。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    package com.jk.ref;

      

    class People{

    String name;

    private static String country="中国";

    public People(String name){

    this.name=name;

    }

    public void tell(){

    System.out.println("name:"+name+"  "+"country:"+country);

    }

    /**

     * @return the country

     */

    public static String getCountry() {

    return country;

    }

    /**

     * @param country the country to set

     */

    public static void setCountry(String country) {

    People.country = country;

    }

    }

    public class StaticDemo01 {

      

    public static void main(String[] args) {

    // TODO Auto-generated method stub

    People.setCountry("shanghai");

    People ps1=new People("zhangsan");

    //People.country="上海";

    ps1.tell();

    People ps2=new People("lisi");

    // ps2.country="上海";

    ps2.tell();

    People ps3=new People("wangwu");

    // ps3.country="上海";

    ps3.tell();

    }

      

    }

    2、父类引用只能调父类和子类重写方法,父子同名方法不会覆盖而是遮蔽。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    public class TestMain {

    public static void main(String[] args) {

    Super sup = new Sub(); //封装(向上造型)

    sup.m1(); //父类引用无法调子类未重写方法,输出mi in Super

    sup.m2();//调用子类方法m2,继承先构建父类方法,方法名相同覆盖(重写)方法,输出m2 in Sub

    Sub sub = (Sub)sup; //拆箱(向下造型)

    sub.m1(); //调用子类静态方法m1,先构建父类方法,方法名相同方法名相同遮蔽方法,输出m2 in Sub

    sub.m2();//调用子类方法m2,继承先构建父类方法,方法名相同覆盖(重写)方法,输出m2 in Sub

    }

    }

    class Super{ //父类

    public static void m1() { //父类静态方法

    System.out.println(“m1 in Super”);

    }

    public void m2() { //父类方法

    System.out.println(“m2 in Super”);

    }

    }

    class Sub extends Super{ //子类

    public static void m1() { //子类静态方法

    System.out.println(“m1 in Sub”);

    }

    public void m2() { //子类方法

    System.out.println(“m2 in Sub”);

    }

    }

    以上就是java中使用static的注意点,在具体操作的时候,一定不要忽略了这两个使用事项,这也是新手练习时经常遇到的出错点。更多Java学习指路:java教程

    专题推荐:java static
    上一篇:Java线程状态有哪几种 下一篇:java之jvm加载器有几种?

    相关文章推荐

    • java中fina和static的区别是什么?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网