zoukankan      html  css  js  c++  java
  • 私有构造函数的特点和用途

    本篇体验私有构造函数的特点,以及在何种情况下使用私有构造函数。

    □ 带私有构造函数的类不能被继承

    在Animal类中声明一个私有构造函数,让Dog类来继承Animal类。

        public class Animal
    
        {
    
            private Animal()
    
            {
    
                Console.WriteLine("i am animal");
    
            }
    
        }
    
        public class Dog : Animal
    
        {
    
            
    
        }
    

      生成解决方案,报错如下:   
    1

    □ 带私有构造函数的类不能被实例化

        class Program
    
        {
    
            static void Main(string[] args)
    
            {
    
                Animal animal = new Animal();
    
            }
    
        }
    
        public class Animal
    
        {
    
            private Animal()
    
            {
    
                Console.WriteLine("i am animal");
    
            }
    
        }
    

    生成解决方案,报错如下:
    2

    □ 私有构造函数的应用

    有些时候,我们不希望一个类被过多地被实例化,比如有关全局的类、路由类等。这时候,我们可以为类设置构造函数并提供静态方法。

        class Program
    
        {
    
            static void Main(string[] args)
    
            {
    
                string str = Animal.GetMsg();
    
                Console.WriteLine(str);
    
                Console.ReadKey();
    
            }
    
        }
    
        public class Animal
    
        {
    
            private Animal()
    
            {
    
                Console.WriteLine("i am animal");
    
            }
    
            public static string GetMsg()
    
            {
    
                return "Hello World";
    
            }
    
        }
    

    总结:一旦一个类被设置成私有构造函数,就不能被继承,不能被实例化,这种情况下,通常为类提供静态方法以供调用。

  • 相关阅读:
    mysql执行sql脚本
    Eclipse Memory Analyzer 进行堆转储文件分析
    JAVA字符串格式化-String.format()
    rpm 使用
    md5sum 使用
    Spring Security 初探
    java工厂模式
    Linux 定时任务
    Java Map 知识
    【转】MVC 比较
  • 原文地址:https://www.cnblogs.com/darrenji/p/3907448.html
Copyright © 2011-2022 走看看