Java&static关键字继承.V05

2022/4/3 20:19:52

本文主要是介绍Java&static关键字继承.V05,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!



[BigDataJava:Java&static关键字继承.V05]                                                                 [BigDataJava.面向对象][|static关键字和继承|Singleton和SingletonTest类的框架实现|singleton类和singletontest类的完整实现|]










一、Singleton和SingletonTest类的框架实现

### --- 案例题目(重中之重)

~~~     ——>        编程实现Singleton类的封装。
~~~     ——>        编程实现SingletonTest类对Singleton类进行测试,要求main方法中能得到且只能得到该类的一个对象。

二、编程代码

### --- 编程代码:编程实现SingLeton类的封装

/*
    编程实现Singleton类的封装
 */
public class Singleton {
    
    // 2.声明本类类型的引用指向本类类型的对象,使用private static关键字共同修饰
    //private static Singleton sin = new Singleton();  // 饿汉式
    private static Singleton sin = null;               // 懒汉式
    
    // 1.私有化构造方法,使用private关键字修饰
    private Singleton() {}
    
    // 3.提供公有的get方法负责将对象返回出去,使用public static关键字共同修饰
    public static Singleton getInstance() {
        //return sin;
        if(null == sin) {
            sin = new Singleton();
        }
        return sin;
    }
}

三、编程代码:编程实现singletontest类的测试

### --- 编程代码:编程实现singletontest类的测试

/*
    编程实现Singleton类的测试
 */
public class SingletonTest {
    
    public static void main(String[] args) {
        
        // 1.声明Singleton类型的引用指向该类型的对象
        //Singleton s1 = new Singleton();
        //Singleton s2 = new Singleton();
        //System.out.println(s1 == s2); // 比较变量s1的数值是否与变量s2的数值相等  false
        //Singleton.sin = null;  可以使得引用变量无效
        Singleton s1 = Singleton.getInstance();
        Singleton s2 = Singleton.getInstance();
        System.out.println(s1 == s2); // true
    }
}

四、编译打印

### --- 编译

C:\Users\Administrator\Desktop>javac SingletonTest.java
### --- 打印输出

C:\Users\Administrator\Desktop>java SingletonTest
true








===============================END===============================


Walter Savage Landor:strove with none,for none was worth my strife.Nature I loved and, next to Nature, Art:I warm'd both hands before the fire of life.It sinks, and I am ready to depart                                                                                                                                                   ——W.S.Landor





来自为知笔记(Wiz)



这篇关于Java&static关键字继承.V05的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程