Java中static和私有化的示例分析-创新互联

这篇文章将为大家详细讲解有关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和私有化的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

网站名称:Java中static和私有化的示例分析-创新互联
网站地址:https://www.cdcxhl.com/article0/dhdsoo.html

成都网站建设公司_创新互联,为您提供网站建设响应式网站App开发ChatGPT网站设计网站维护

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

手机网站建设