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
Ans. Class without any access specifier has the default scope i.e it can be accessed by any class within same package. Class declared public can be accessed from anywhere.
The general concept is that class is an object and className is "one" of its properties.
It's just the name of the class.
A public class will have access specifier "public" and its members can be accessed with in and out of the class in which they are specified. A class which doesnt have the public access specifier are called as non-public classes and its member can be accessed only within the class in which they are specified.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With