Java - The difference between class “ClassName” and public class “ClassName”

眉间皱痕 提交于 2020-01-09 12:41:52

问题


What's the difference between

class x {
    //code here
}

and

public class x {
    //code here
}

Sometimes I see examples on the Internet and they'll have public class instead of class and they're all simple programs. I use class for my assignments and so does everybody else


回答1:


The first one will result in your class being assigned the default visibility, that is package-private (ie: accessible within the same package).

The second one makes it public, that is, visible to any other class.

Reference: Controlling Access to Members of a Class




回答2:


The simplest way to put it:

if everything you have is in the same package (package com.myschool.myapp at the top of every file) then there is no difference, but if anything wants to access anything outside it's package then it must be public.

For instance, "String" is in "java.lang", your package almost certainly isn't in java.lang so if string wasn't public you couldn't access it.




回答3:


  • The former is "package visibility" or "default visibility", where the class is only visible to classes in the same package.
  • The latter is "public visibility", where the class is visible to any other class.

There also exists the following visibility modifiers for members and methods and inner classes:

  • "Protected visibility" is the same as package, except that any class that inherits the class defined with protected scope can also access it.
  • "Private visibility" means that the class is only accessible to
    itself.



回答4:


The first one will be default class, i.e it cannot be accessed in any other package except itself, but can be accessed by other classes in the same package.

The second one makes it public,i.e, you can access it from any class of any package just like you access String and Array which are if different packages.

Remember, we are talking about accessible from packages not class.

Regarding, And then: If I have a class X (please capitalize the class name) that is not declared as public, can I have public instance variables (EG public String name;) in it?? ;)

Yes of course you can have public instance variables in non-public class.



来源:https://stackoverflow.com/questions/7641876/java-the-difference-between-class-classname-and-public-class-classname

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!