java单例类

xiaoxiao2021-02-28  107

单例类:如果一个类始终只能创建一个实例,则这个类被称为单例类。 错误代码:

点击(此处)折叠或打开

class Singleton{     private static Singleton instance;     private Singleton(){}     public static Singleton getInstance()     {         if (instance == null)         {             return new Singleton();//如果这样写的话会返回false,因为创建了两个对象         }         return instance;     } } public class Hello {     public static void main(String[] args)     {         Singleton instance1 = Singleton.getInstance();         Singleton instance2 = Singleton.getInstance();         System.out.println(instance1==instance2);         //polymorphicBc.sub();                                } } 正确写法

点击(此处)折叠或打开

class Singleton{     private static Singleton instance;     private Singleton(){}     public static Singleton getInstance()     {         if (instance == null)         {             instance = new Singleton();         }         return instance;     } } public class Hello {     public static void main(String[] args)     {         Singleton instance1 = Singleton.getInstance();         Singleton instance2 = Singleton.getInstance();         System.out.println(instance1==instance2);         //polymorphicBc.sub();                                } } 运行结果为true。 关于static方法的小知识点:

点击(此处)折叠或打开

class NullData {     public static void test()     {         System.out.println("Hello");     } } public class Hello {        public static void main(String[] args)        {            NullData nd = null;             nd.test();         } } 运行结果是:Hello 表明null对象可以访问它所属类的成员。如果一个null对象访问实例成员将会引发NullPointException异常,因为null 表明该实例根本不存在,那么它的实例变量和实例方法自然也不存在。 <script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script> 阅读(11) | 评论(0) | 转发(0) | 0

上一篇:java初始化块

下一篇:匿名内部类

相关热门文章 Tomcat 6 配置SSI让Resin支持shtml(SSI)- 静...tomcat + ssiASP JavaScript Lessons(8-14)JDK1.6官方下载_JDK6官方下载_... 给主人留下些什么吧!~~ 评论热议
转载请注明原文地址: https://www.6miu.com/read-58671.html

最新回复(0)