java私有静态变量_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();

}

}

输出结果为:

hello

hello

hello

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

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

希望本文所述对大家java程序设计有所帮助。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值