Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - The difference between class "ClassName" and public class "ClassName"

Tags:

java

class

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

like image 930
Alex Avatar asked Oct 03 '11 23:10

Alex


People also ask

What is the difference between public class and class in Java?

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.

What is the difference between class and className?

The general concept is that class is an object and className is "one" of its properties.

What is the className of a class Java?

It's just the name of the class.

What is the difference between public and non public class in Java?

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.


2 Answers

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

like image 161
NullUserException Avatar answered Sep 19 '22 01:09

NullUserException


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.

like image 31
Bill K Avatar answered Sep 17 '22 01:09

Bill K