Java - The difference between class “ClassName” an

2019-01-21 17:12发布

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

标签: java class
4条回答
做个烂人
2楼-- · 2019-01-21 17:20

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

查看更多
孤傲高冷的网名
3楼-- · 2019-01-21 17:22

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.

查看更多
放我归山
4楼-- · 2019-01-21 17:30
  • 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.
查看更多
何必那么认真
5楼-- · 2019-01-21 17:33

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.

查看更多
登录 后发表回答