zoukankan      html  css  js  c++  java
  • Java中的static(静态变量)和私有化

    1、static作用主要有两方面:其一,当希望类中的某些属性被所有对象共享,则就必须将其声明为static属性;其二,如果一个类中的方法由类名调用,则可以将其声明为static方法。

    2、需要注意的是,非static声明的方法可以去调用statci声明的属性和方法;但是static声明的方法不能调用非static类型的声明的属性和方法。

    3、static方法调用static变量

    1 public class Pvf {
    2     static boolean Paddy;
    3     public static void main(String[] args) {
    4         System.out.println(Paddy);
    5     }
    6 
    7 }

    输出结果为false

    分析:变量被赋予了默认值false。

    4、static方法调用非static变量

    1 public class Sytch {
    2     int x = 20;
    3     public static void main(String[] args) {
    4         System.out.println(x);
    5     }
    6 
    7 }

    输出结果为:

    Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    Cannot make a static reference to the non-static field x

    at test02.Sytch.main(Sytch.java:6)

    5、

     1 public class Sundys {
     2     private int court;
     3     public static void main(String[] args) {
     4         Sundys s = new Sundys(99);
     5         System.out.println(s.court);
     6     }
     7     Sundys(int ballcount) {
     8         court = ballcount;
     9     }
    10 
    11 }

    输出结果为:99

    分析:私有化变量仍可以被构造方法初始化。

    6、私有化的一个应用是单例设计模式

     1 class Singleton{
     2     private static Singleton instance = new Singleton();
     3     private Singleton(){
     4     }
     5     public static Singleton getInstance(){
     6         return instance;
     7     }
     8     public void print(){
     9         System.out.println("hello");
    10     }
    11 }
    12 public class SingleDemo05 {
    13 
    14     public static void main(String[] args) {
    15         Singleton s1 = Singleton.getInstance();
    16         Singleton s2 = Singleton.getInstance();
    17         Singleton s3 = Singleton.getInstance();
    18         
    19         s1.print();
    20         s2.print();
    21         s3.print();
    22         
    23     }
    24 
    25 }

    输出结果为:

    hello
    hello
    hello

    分析:虽然声明了3个Singleton对象,但实际上所有的对象都只使用instance引用,也就是说,不管外面如何,最终结果也只有一个实例化对象存在。此即为单例设计模式。

     由此可知,只要将构造方法私有化,就可以控制实例化对象的产生。

  • 相关阅读:
    POJ 2342
    SHU 413
    SHU 414
    进制转换模板
    SHU 第15届上海大学程序设计联赛夏季赛[热身赛] 第三题(G题)
    POJ 3185
    XTU 1260
    高斯消元法模板
    POJ 2057
    模态窗口的定时关闭
  • 原文地址:https://www.cnblogs.com/XuGuobao/p/7236330.html
Copyright © 2011-2022 走看看