温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java中static和私有化的示例分析

发布时间:2021-09-28 14:13:12 来源:亿速云 阅读:120 作者:小新 栏目:编程语言

这篇文章将为大家详细讲解有关Java中static和私有化的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

具体如下:

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

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

3、static方法调用static变量

public class Pvf {  static boolean Paddy;  public static void main(String[] args) {    System.out.println(Paddy);  }}

输出结果为

false

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

4、static方法调用非static变量

public class Sytch {  int x = 20;  public static void main(String[] args) {    System.out.println(x);  }}

输出结果为:

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、

public class Sundys {  private int court;  public static void main(String[] args) {    Sundys s = new Sundys(99);    System.out.println(s.court);  }  Sundys(int ballcount) {    court = ballcount;  }}

输出结果为:

99

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

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

class Singleton{  private static Singleton instance = new Singleton();  private Singleton(){  }  public static Singleton getInstance(){    return instance;  }  public void print(){    System.out.println("hello");  }}public class SingleDemo05 {  public static void main(String[] args) {    Singleton s1 = Singleton.getInstance();    Singleton s2 = Singleton.getInstance();    Singleton s3 = Singleton.getInstance();    s1.print();    s2.print();    s3.print();  }}

输出结果为:

hellohellohello

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

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

关于“Java中static和私有化的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI