Only one public class in java

Class Access Modifiers

A Java class can be declared with an access modifier to specify how it will be accessed by the other classes in Java, and this access modifier is known as class access modifier. Let us see different kinds of class access modifiers.

Public Access Modifier

  • In this code, we have created two classes, A(in A.java)and B(in B.java)
  • Class A is declared public and that’s why it is visible and accessible to the class B. Hence, there is no compile error when B.java is compiled, even though it is accessing class A and creating its object.

Note :

To use a public class declared in a different package, you will still have to import it.

There can be only public class defined in one .java file

There can only be one public class defined in a .java file, and the name of this class should match with the name of .java file in which it is defined and saved, otherwise Java Compiler will throw a compiler error.

On compiling this class, we have received a compile error :

D:\Java>javac A1.java A1.java:1: error: class A is public, should be declared in a file named A.java public class A ^ 1 error 

Default Access Modifier

When two default classes exist in the same package

Class A and class B exist in the package, pack1. Hence, when class A was accessed in the code of B class, we have received no compile error in the compilation of B.java.

When two default classes exist in the different package

If you try to access a default class from a class that belongs to a different package, it would lead to a compile error. Let’s understand this by an example —

After compiling :

B.java:7: error: cannot find symbol A ob = new A(); ^ symbol: class A location: class B B.java:7: error: cannot find symbol A ob = new A(); ^ symbol: class A location: class B 2 errors > 

Class A exists in the package, pack1, while Class B exists in the package, pack2. Hence, we have received compile errors on the compilation of B.java, clearly stating that the compiler couldn’t find class A when accessed in the code of B.java

Источник

Why only 1 public class in Java file

final method : the method cannot not be overridden. final class : the class cannot extended. 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.

Why only 1 public class in Java file

In any Java file, why can we have only one public class whose name is same as the Java file name?

It forces all Java code to be organized in a certain way , which in the long run helps improve code readability .

The Java designers chose a strict approach that enforces their idea of good design practices, and this is part of that theme. Contrast that with the anything-goes attitude in Perl.

Читайте также:  Html meta favicon png

According to this source, it is for efficient compilation :

In the sidebar it explains why: «This restriction is not yet enforced by the compiler, although it’s necessary for efficient package importation»

It’s pretty obvious — like most things are once you know the design reasons — the compiler would have to make an additional pass through all the compilation units (.java files) to figure out what classes were where, and that would make the compilation even slower.

The same applies also for imports of source files in IDEs. Another reason would be reasonable source sizes.

These are the rules. Although it is not quite true. You can define internal classes inside you «main» class like this:

Courtesy of Dr Heinz Kabutz and his excellent newsletter.

Why is each public class in a separate file?

This is a question that I have frequently been asked during my courses. Up to now I have not had a good answer to this question. In section 1, we read: «Although each Oak compilation unit can contain multiple classes or interfaces, at most one class or interface per compilation unit can be public».

In the sidebar it explains why: «This restriction is not yet enforced by the compiler, although it’s necessary for efficient package importation»

It’s pretty obvious — like most things are once you know the design reasons — the compiler would have to make an additional pass through all the compilation units (.java files) to figure out what classes were where, and that would make the compilation even slower.

Public vs Protected Access Modifier in Java, Similarly, a member or method, or interface is declared as public as we can access that member from anywhere. Protected Access Modifier: This …

Utilizing Public Final Classes Java

I would just like a clear example of how to instantiate a public final class in Java. I have to use a method from a class like this for a project, and have no idea how to instantiate it in the first place. Very difficult to find a clear example and explanation of the proper syntax. Thanks for the help.

public class Test < public static void main(String[] args) < Project pro = new Project(); pro.getName(); >> final class Project < public String getName()> 

A final class can be created like a normal class, Only thing is it can not be extended

public class del < public static void main(String args[]) < x x1=new x(); System.out.println(x1.u()); >> final class x < public String u() < return "hi"; >> 

As you can see,x is a final class and have a method u which returns a string. I am instatiating x in class del and calling its method u. The output is hi

For more info click on final

final class Test < public void callMe()< System.out.println("In callMe method."); >> public class TestingFinalClass < public static void main(String[] args)< Test t1 = new Test(); t1.callMe(); >> 

final in java is applied to variable,method,class

  1. final variable : the variable can not be signed with another value.
  2. final method : the method cannot not be overridden.
  3. final class : the class cannot extended.

The best example is String class in java. public final class String you can access the methods of String class as normal.
Some links

public class Test < public static void main(String[] args) < StdRandom stdRandom = StdRandom.getInstance(); /* this will retun an instance of the class, if needed you can use it */ int result =StdRandom.uniform(1); System.out.println(result); >> final class StdRandom < private static StdRandom stdRandom = new StdRandom(); private StdRandom()< >public static StdRandom getInstance() < return stdRandom; >public static int uniform(int N) < // Implement your logic here return N; >> 

Java — Difference between «public» and «void», Jul 9, 2016 at 14:46. public is an access specifier which means the method can be accessed from anywhere, void is just a type. – Nongthonbam …

Читайте также:  Creating text files in java

Java — The difference between class «ClassName» and public class «ClassName»

What’s the difference between

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

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

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.

  • 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.

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.

Class — Utilizing Public Final Classes Java, final in java is applied to variable,method,class. final variable : the variable can not be signed with another value. final method : the method cannot …

Protected/public Inner Classes

Can someone please explain to me what is the difference between protected / public Inner classes?

I know that public inner classes are to avoid as much as possible (like explained in this article).

But from what I can tell, there is no difference between using protected or public modifiers.

Take a look at this example:

public class Foo1 < public Foo1() < >protected class InnerFoo < public InnerFoo() < super(); >> > 
public class Foo2 extends Foo1 < public Foo2() < Foo1.InnerFoo innerFoo = new Foo1.InnerFoo(); >> 

All of this compiles and is valid whether I declare InnerFoo protected or public .

What am I missing? Please, point me out a case where there’s a difference in using protected or public .

Читайте также:  What is lightbox css

The protected access modifier will restrict access from classes other than the ones in the same package and its subclasses.

In the example shown, the public and protected will have the same effect, as they are in the same package.

For more information on access modifiers, the Controlling Access to Members of a Class page of The Java Tutorials may be of interest.

You can just think protected inner class is protected member, so it only access for class, package, subclass but not for the world.

In addition, for outter class, there is only two access modifier for it. Just public and package.

Weird thing in java:

Pure Java: You cannot return a private inner class from a public getter.

In JSP : You cannot return a non-public inner class from a public getter.

Java Demo You Can Run:

public class ReturnInnerClass< public static void main(String []args)< MyClass inst = new MyClass("[PROP_VAL]"); System.out.println( inst.get().myProperty() );; >;; >;; class MyClass < //:If JSP: MUST be public //:Pure Java: //: public,protected,no-access-modifier //: Will all work. //:Private fails in both pure java & jsp. protected class Getters< public String myProperty()< return(my_property); >>;; //:JSP EL can only access functions: private Getters _get; public Getters get() < return _get; >private String my_property; public MyClass(String my_property)< super(); this.my_property = my_property; _get = new Getters(); >;; >;; //:How to run this example: //: 1: Put this code in file called: "ReturnInnerClass.java" //: 2: Put ReturnInnerClass.java into it's own folder. //: ( Folder name does not matter.) //: 3: Open the folder. //: 4: Right-Click --> GitBashHere //: 5: In command prompt within folder: //: 5.1: javac ReturnInnerClass.java //: 5.2: java ReturnInnerClass //: ( javac: java compiler ) //: ( java : runs compiled java program ) //: EXPECTED OUTPUT: //: [PROP_VAL] 

For JSP , put only the class code above into folder: com/myPackage/MyClass and put «import com.myPackage.MyClass» as first line of source code. Then create a new .jsp page with this source code:

Stack Used: Java8 + Tomcat9

Java — protected/public Inner Classes, That is classes in packages prefixed by the package name of the declaring class will not have access. You can just think protected inner class is protected …

Источник

How many public classes of the same name it can have in Java?

A Java file contains only one public class with a particular name. If you create another class with same name it will be a duplicate class. Still if you try to create such class then the compiler will generate a compile time error.

Example

public class Example < >public class Example < public void sample()< System.out.println("sample method of the Example class"); >public void demo() < System.out.println("demo method of the Example class"); >public static void main(String args[]) < Example obj = new Example(); obj.sample(); obj.demo(); >>

Error

C:\Sample>javac Example.java Example.java:6: error: duplicate class: Example public class Example< ^ 1 error

In fact, you can’t create two public classes in a single file, Only one class should be public and it should be the name of the class.

If you try to create two public classes in same file the compiler generates a compile time error.

Example

public class Sample < >public class Example < public void sample()< System.out.println("sample method of the Example class"); >public void demo() < System.out.println("demo method of the Example class"); >public static void main(String args[]) < Example obj = new Example(); obj.sample(); obj.demo(); >>

Error

C:\Sample>javac Example.java Example.java:2: error: class Sample is public, should be declared in a file named Sample.java public class Sample < ^ 1 error

Swarali Sree

I love thought experiments.

Источник

Оцените статью