为什么我在Java中收到有关实用程序类的警告 [英] Why am I getting this warning about utility classes in Java

查看:126
本文介绍了为什么我在Java中收到有关实用程序类的警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Java和OOPS,在eclipse中编写一个基本的Hello World时,我看到一个黄色三角形告诉我'实用程序类不应该有公共或默认构造函数'。我无法理解为什么会发生这种情况,这是什么意思?我做错了什么?

I'm learning Java and OOPS and while programming a basic Hello World in eclipse, I see a yellow triangle telling me 'utility classes should not have a public or default constructor'. I'm not able to understand why exactly is this happening and what does it mean? What am I doing not right?

class HelloWorld {


public static void main(String[] args)
{
    // TODO Auto-generated method stub
            System.out.println("Hola Mundo!");

}


  }

EDIT1:编辑代码以包含建议的更改。

Edited the code to include changes suggested.

final class HelloWorld {


private HelloWorld()
{
    throw new AssertionError("Instantiating utility class...");

}
public static void main(String[] args)
{
    // TODO Auto-generated method stub
            System.out.println("Hola Mundo!");

}


}

仍在线上类HelloWorld获得警报。

Still getting the alert on the line Class HelloWorld.

Edit2:

创建一个新类,现在它作品。谢谢Jon.为什么旧班仍然会发出警告?波希米亚人我仍然不了解你在帖子中提到的概念。一旦我有了更好的主意,我会回到他们身边。谢谢你解释一下。

Created a new class and now it works. Thanks Jon.Why does the old class still give warning? Bohemian I'm still not aware about the concepts mentioned by you in your post. I would come back to them once I get a better idea. Thank you for explaining things.

推荐答案

这意味着有人可以写:

HelloWorld helloWorld = new HelloWorld();

当你可能不希望他们 - 你不是提供任何实例成员,为什么允许他们创建实例?将代码重写为:

when you probably don't want them to - you're not providing any instance members, so why allow them to create instances? Rewrite your code as:

final class HelloWorld {

    private HelloWorld() {
        // Prevent instantiation
        // Optional: throw an exception e.g. AssertionError
        // if this ever *is* called
    }

    public static void main(String[] args) {
        System.out.println("Hola Mundo!");
    }
}

这篇关于为什么我在Java中收到有关实用程序类的警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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