I'm confused as to what this is called in Java and what this does:
public class MainFrame(){
public static void main(String[] args{
//etc.
}
}//end class
class SampleMenuListener implements MenuListener(){
}//end SampleMenuListener
I researched inner classes and know how to use anonymous inner classes however I know this is not one and after some googling I couldn't figure out what this is called in Java. So my questions are what is this called? And in Eclipse the Class C shows up next to class SampleMenuListener. So is this essentially the same thing as making a new class in the same project folder called SampleMenuListener and making an instance of it in MainFrame? And if so is this simply just a shorthand way of writing another class without making it separate in eclipse? Or does it some how differ and how does it differ? Definitely feel free to post links as this may be a stupid question but like I said I couldn't seem to google the right keywords to get results on what this is called in Java.
Normally, we like to say that Java can only have one class per code file, and that the source file must be named for the class. This isn't entirely true. The actual rule is that you can only have one public class per code file. You can have as many as you want (but please don't...), so long as no more than one of them is public.
The others must be package access (no access specifier). See the relevant documentation.
In your example SampleMenuListener is simply a class like any other.
This is a normal class , it is just written in same .java file.
only difference is there is only one public class allowed(as file name need to be same as of public class )
Related
Hi I have a question on Java Package. I have created a package with more than one classes [package name is 'animal' and file name is 'Zoo.java']. I have created another java file which is in another package 'mypackage' and created a file called 'MAIN.java'. I tried accessing members of the 'animal' package from 'MAIN.java' and it is throwing me an error because it cannot access classes of 'animal' package. I know that only classes which are in same package should be accessible each other, or it should make as public. But I can only change one class to public in 'Zoo.java'. So I found one solution that create separate java files for each class in animal package and make it as public. Is there any other method ? My understanding was, we can write all classes in one file and import them from anywhere. Below is my screenshot.
And one more thing, in java library how they are implemented it? separate source files for each class within a package ?
So I found one solution that create separate java files for each class in animal package and make it as public.
If you want to use classes outside of the package they're defined in, yes, they have to be public. And only the public parts of them are accessible, except to subclasses, which also have access to the protected parts of them. More in this tutorial.
And yes, there can be only one public class in a given file (and the file's name must match the public class's name). In Java, we tend toward doing that anyway. It helps avoid files getting huge and difficult to work in.
Is there any other method ? My understanding was, we can write all classes in one file and import them from anywhere.
I'm not sure where you would have got that understanding from. To use classes outside their packages, they have to be public, and to be public they have to be in separate files.
From your comment on another answer:
...in my case if i made Elephant as public in Zoo.java then I can only access that particular class outside not others like Fish and Bird.
Right. If you want them all to be public, rather than having Zoo.java, have Elephant.java, Fish.java, and Bird.java.
You have another way to solve your problem. You can use inner class as follow.
package animals;
public class Elephant {
public static class Fish{
public void print(){
System.out.println("test");
}
}
}
and in main package:
package main;
import animals.Elephant;
public class Main {
public static void main(String[] args) {
Elephant.Fish fish = new Elephant.Fish();
fish.print();
}
}
But it is not recommended design. If design is necessary define seperate java file and mark as public. it is the best way.
There can be multiple classes inside one JAVA file provided that only a single Class is made Public.
See this
Multiple classes in single file
In this case you can use inner classes. See the following example.
Here the inner class is accessible from classes in other packages.
public class Outer {
public class Inner {
}
}
I am trying to write tests for a piece of code that uses the inner class of the following object as an input (I've generalized the names).
public class MockOuterClass implements OuterClass, Mock {
static class MockInnerClass implements InnerClass {
//fields and methods of the nested class
}
//methods of the outer class
}
Now since the inner class does not have a visibility tag, it defaults to "protected." Here lies my issue: since my tests and source code are in separate packages, how can I create an instance of this inner object? I attempted this:
MockOuterClass.MockInnerClass test = new MockOuterClass.MockInnerClass();
When I do this, Eclipse says that this line is unacceptable (which I assumed was the case, but it was wishful thinking) since MockInnerClass defaults to protected and thus cannot be used outside its package. Is there a way I can use this class somehow? I did not write the source code, so I am unsure if the lack of a "public" tag on the inner class was intentional or the programmer's mistake.
Thank you in advance.
A bit of an aside, not an actual answer, but I have always put my tests into the same package as the classes being tested. At least, as much as possible, there are a few very rare cases where this is impossible.
Why are you using a different package? Is there a good reason to do so?
Now, back to an answer, if you insist on testing from a separate package, unless MockOuterClass exposes some method to construct (or expose) the MockInnerClass, you are stuck. (I guess you could try using Reflection but that is getting desperate.) However, as several have commented, the author of the class "intended" for the inner class to be hidden, a. la. Kent Beck.
In other words, if you follow Kent Beck, you should be writing tests that target MockOuterClass, NOT MockInnerClass. The inner class is a "non public detail".
If this code wasn't written by you and declares a non-public static class (side-note: it defaults to package-protected, which is very different to protected), chances are the writer intends to hide the class from your use. In short, there is no way to access the class from outside the package, and you probably shouldn't be trying to.
I know these questions may sound stupid, but in Java, what are Auxiliary classes, how does some one write one, and how does the compiler know that something is an Auxiliary class?
Edit:
The reason I ask this is because the compiler is generating a warning regarding an object in an external library, and I want to know why.
Edit 2:
Here is the compiler warning for those who want it:
warning: auxiliary class Pattern in jregex/Pattern.java should not be accessed from outside its own source file
As descried in Java specification here, you can specify more than one class in one .java file. The class which name matches .java file name will be the main class which can be declared public and be visible to other classes. All other classes in the file therefore are "auxilary" classes. Auxilary class can NOT be declared public and (as #trashgod rightfully pointed out) therefore they only be declared with package-private access. For instance for AClass.java file:
public class AClass {
private AuxilaryClass a;
}
class AuxilaryClass {
private int b;
}
AuxilaryClass class can't be public and is not visible outside this AClass.java file.
However, using auxilary classes considered extremely bad style and against Java Code Convention. Please use separate or inner classes if really needed.
Edit: The term "Auxilary" is not Oracle/Sun official terminology. It has been introduced (or used) here: http://www.youtube.com/watch?v=miTM9rY3He0 and/or here: http://doc.sumy.ua/prog/java/langref/ch05_03.htm
An auxiliary class isn't any kind of official or technical thing as far as I know. Someone might describe a class as auxiliary if it were addressing a secondary concern, or something, but the compiler doesn't have any idea what an auxiliary class is, and neither do I.
In general, if you have error messages from the computer, please paste them in their entirety. If you think the compiler is upset about an auxiliary class, paste the error message: someone else will be able to make sense of it, whereas currently it's being filtered through some kind of confusion that's made you think auxiliary classes are a real thing!
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.
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:
public class A {
public class B {
...
}
}
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.
We can have only one top level public either class or interface in any java compilation unit ( .java source file ).
But there can be any number of default classes/interfaces per src file.
why:
JLS leaves the option to the java compiler. And most of the compiler implementations force to have file name same as :
(1) the public class/interface name
(2) if there is a main method and no public class then any name
(3) If there is main method and public class then main method should be in that public class
(4) if there is no public class and no main method then any valid name which may or may not be matching with the class/interface names in the file.
From (2): If two public classes allowed, we should give the file two names which is terribly meaningless to file system.
From (3): If two public classes allowed, we should have two main methods which is terribly meaningless to java
Hence a Java source file can have one only public class.
I think the above 4 points are forced by compiler to make the job of both compiler and jvm to find particular java source file or class file easy-so-quick for the compilation/loading/linking. Java has such built in restrictions which developers should follow to have better programming.
Source: My readings and understanding.
To understand the basic reason behind these restrictions, let's suppose compiler doesn't give compile error for not naming file name same as public class name.
Suppose there is a package A
A
/ \
file1.java file2.java
file1.java
package A;
class file1
{
public static void main(String args[])
{
}
}
public class file3
{
public static void main(String args[])
{
}
}
Now as we know that a public class can also be accessed outside the package, now it will become the responsibility of a developer to make it accessible to the outside world. Let's see how:
Suppose package A is containing only Java files(no class files) and some class outside the package A tries to access public class file3, compiler will first try to find file3.class ( not available ), then it will try to find file3.java ( not available ). So even though file3 class is public in nature, it is not visible to the outside world. So if a compiler puts the restriction that if a file is containing public class, it should be named same as the public class name, then above issue can be resolved and the developer won't have to think of exposing public class to the outside world.
Compiler also puts the restriction that there should be atmost one public class per Java file, so that every public class can be accessed by the outside world.
Java utilizes this convention to find class/interface bytecode by starting at the classpath and scanning for the package hierarchy in subdirectories. Filesystem representation of this hierarchy also enforces some basic rules.
Any two Java classes or interfaces
in the same package cannot have the
same name. File names would
conflict.
Any two Java packages in
the same parent package could not
have the same name. Folder paths
would conflict.
A class has visibility to all classes in the same package without modification
to the classpath.
To have an understanding between the compiler and the programmer.It is a rule that the source code must have atmost one public class and that class must contain the main function.So without any confusion/restriction the compiler can access(public) the class and name the class name to the class file.Also since this class contains the main(), executing the class file will give correct flow
Public modifier with a class is exposed to the world that means any other class which is outside of the package can also access it to resolve dependency.
Now this dependency chain containing multiple classes are verified two times - one is while compilation ( one level of dependency is verified) & other one is while execution ( whole dependency chain is verified ).
Now suppose there is public class (class A) whose source file name is something different from class name. Now if some other class (say class B) depends on it , then while compilation of class B , java compiler will surely check where that class A is located & for that compiler has to go thru all the packages in search of class A ,which is time consuming.
Now suppose in the same scenario we give source file name of class A as A.java , then while compiling class B , compiler will search for class A & for that it only need to find source file whose name is A.java , so it doesn't need to go thru all packages ( which may contain multiple classes) it will now only search that package in which a source file A.java is present.
So from compilation time , performance point if view one source file should have one public class.
It enables a more efficient lookup of source (.java) and compiled (.class) files during compilation (import directive) and a more efficient classloading during execution. The idea being: if you know the name of a class, you know where it should be found for each classpath entry. No indexing required.
I think that this may be a possible reason.
There can be only one public class in a java file because the name of java file is same as the name of public class.And obviously we can't have a file with two different names.
It is how it has been designed and I am not sure if the reason is documented. But here is a good reason on why it is done that way. Let's assume we have two public classes Y & Z in a file named Y.java. Now, let's assume a different class X is using Z. Now, when we compile X, the compiler first tries to locate Z.class and if it cannot find it, then it tries to locate Z.java so that it can compile it automatically. But, since we only have Y.java, the class Z cannot be located and hence we get a compilation error. So, we do need to place them in separate files.
Class A{
}
public Class B{
}
So this is correct becoz A is not public and compiler will not confuse that which class compiler should execute.
public Class A{
}
public Class B{
}
So this is incorrect becoz here compiler get confused which class should execute becoz both are public.
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.
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:
public class A {
public class B {
...
}
}
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.
We can have only one top level public either class or interface in any java compilation unit ( .java source file ).
But there can be any number of default classes/interfaces per src file.
why:
JLS leaves the option to the java compiler. And most of the compiler implementations force to have file name same as :
(1) the public class/interface name
(2) if there is a main method and no public class then any name
(3) If there is main method and public class then main method should be in that public class
(4) if there is no public class and no main method then any valid name which may or may not be matching with the class/interface names in the file.
From (2): If two public classes allowed, we should give the file two names which is terribly meaningless to file system.
From (3): If two public classes allowed, we should have two main methods which is terribly meaningless to java
Hence a Java source file can have one only public class.
I think the above 4 points are forced by compiler to make the job of both compiler and jvm to find particular java source file or class file easy-so-quick for the compilation/loading/linking. Java has such built in restrictions which developers should follow to have better programming.
Source: My readings and understanding.
To understand the basic reason behind these restrictions, let's suppose compiler doesn't give compile error for not naming file name same as public class name.
Suppose there is a package A
A
/ \
file1.java file2.java
file1.java
package A;
class file1
{
public static void main(String args[])
{
}
}
public class file3
{
public static void main(String args[])
{
}
}
Now as we know that a public class can also be accessed outside the package, now it will become the responsibility of a developer to make it accessible to the outside world. Let's see how:
Suppose package A is containing only Java files(no class files) and some class outside the package A tries to access public class file3, compiler will first try to find file3.class ( not available ), then it will try to find file3.java ( not available ). So even though file3 class is public in nature, it is not visible to the outside world. So if a compiler puts the restriction that if a file is containing public class, it should be named same as the public class name, then above issue can be resolved and the developer won't have to think of exposing public class to the outside world.
Compiler also puts the restriction that there should be atmost one public class per Java file, so that every public class can be accessed by the outside world.
Java utilizes this convention to find class/interface bytecode by starting at the classpath and scanning for the package hierarchy in subdirectories. Filesystem representation of this hierarchy also enforces some basic rules.
Any two Java classes or interfaces
in the same package cannot have the
same name. File names would
conflict.
Any two Java packages in
the same parent package could not
have the same name. Folder paths
would conflict.
A class has visibility to all classes in the same package without modification
to the classpath.
To have an understanding between the compiler and the programmer.It is a rule that the source code must have atmost one public class and that class must contain the main function.So without any confusion/restriction the compiler can access(public) the class and name the class name to the class file.Also since this class contains the main(), executing the class file will give correct flow
Public modifier with a class is exposed to the world that means any other class which is outside of the package can also access it to resolve dependency.
Now this dependency chain containing multiple classes are verified two times - one is while compilation ( one level of dependency is verified) & other one is while execution ( whole dependency chain is verified ).
Now suppose there is public class (class A) whose source file name is something different from class name. Now if some other class (say class B) depends on it , then while compilation of class B , java compiler will surely check where that class A is located & for that compiler has to go thru all the packages in search of class A ,which is time consuming.
Now suppose in the same scenario we give source file name of class A as A.java , then while compiling class B , compiler will search for class A & for that it only need to find source file whose name is A.java , so it doesn't need to go thru all packages ( which may contain multiple classes) it will now only search that package in which a source file A.java is present.
So from compilation time , performance point if view one source file should have one public class.
It enables a more efficient lookup of source (.java) and compiled (.class) files during compilation (import directive) and a more efficient classloading during execution. The idea being: if you know the name of a class, you know where it should be found for each classpath entry. No indexing required.
I think that this may be a possible reason.
There can be only one public class in a java file because the name of java file is same as the name of public class.And obviously we can't have a file with two different names.
It is how it has been designed and I am not sure if the reason is documented. But here is a good reason on why it is done that way. Let's assume we have two public classes Y & Z in a file named Y.java. Now, let's assume a different class X is using Z. Now, when we compile X, the compiler first tries to locate Z.class and if it cannot find it, then it tries to locate Z.java so that it can compile it automatically. But, since we only have Y.java, the class Z cannot be located and hence we get a compilation error. So, we do need to place them in separate files.
Class A{
}
public Class B{
}
So this is correct becoz A is not public and compiler will not confuse that which class compiler should execute.
public Class A{
}
public Class B{
}
So this is incorrect becoz here compiler get confused which class should execute becoz both are public.