构造函数总是必须公开吗? [英] Do constructors always have to be public?

查看:163
本文介绍了构造函数总是必须公开吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的第一个问题是 -

My first question is -

   class Explain() {
        public Explain() {
      }
   }

应该如何构造函数总是声明为public?

Should Constructor always declared as public?

如果我创建了一个私人构造函数,该怎么办。

What if I create a private constructor.

我总是看到构造函数隐式 public 。那么为什么 private 构造函数是有用的?或者它根本没有用。因为没有人能够调用它,或者永远不会创建一个对象(因为 private 构造函数)!这是我的第二个问题。

I always seen constructors are implicitly public. So why private constructor is useful? Or is it not useful at all. Because nobody could ever call it, or never make an object(because of the private constructor) ! And that is my second question.

推荐答案

不,构造函数可以 public private protected $ c>(根本没有访问权限)。

No, Constructors can be public, private, protected or default(no access modifier at all).

使某物私人不意味着没有人可以访问。它只是意味着类外没有人可以访问它。因此 private 构造函数也很有用。

Making something private doesn't mean nobody can access it. It just means that nobody outside the class can access it. So private constructor is useful too.

private 构造函数的一个用途是提供单例类。单例类是将对象创建的数量限制为一个的类。使用 private 构造函数,我们可以确保一次只能创建一个对象。

One of the use of private constructor is to serve singleton classes. A singleton class is one which limits the number of objects creation to one. Using private constructor we can ensure that no more than one object can be created at a time.

示例 -

public class Database {

    private static Database singleObject;
    private int record;
    private String name;

    private Database(String n) {
        name = n;
        record = 0;
    }

    public static synchronized Database getInstance(String n) {
        if (singleObject == null) {
            singleObject = new Database(n);
        }

        return singleObject;
    }

    public void doSomething() {
        System.out.println("Hello StackOverflow.");
    }

    public String getName() {
        return name;
    }
}

有关 a href =http://stackoverflow.com/q/215497/4533771>访问修饰符。

More information about access modifiers.

这篇关于构造函数总是必须公开吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆