I'm new to Java and i want a refinement:
First of all,i am not sure if i can have 2 classes in the same file.
My question is what is each class when you see this sequence of code:
class Something {
//code here
} //end of class Something
public class SomethingElse {
//NO code here!!!
public static void main(String[] args) {
//code of main here
}//end of main
}
What's the role of the class Something Else and why there is no code inside?I know that is a very stupid question but there are some details that i don't really get and i want some help...
You can have more than one class per file, but only one class can be public and its name must match the name of the file (e.g. public MyClass in MyClass.java).
The public class of a file will be visible to the outside world, and in particular if the class has a public static main(String[] args) method, it can be used to start an application.
In your case for example, once you have compiled your file using javac, you will get files Something.class and SomethingElse.class.
Using the command java SomethingElse will tell the Java Virtual Machine to do the following:
Find the SomethingElse class, which must be in the SomethingElse.class file
call the main method, matching the signature I pasted above on this class (and putting any given argument in the args array).
You cannot call java Something because the class isn't public and doesn't have a main method. But other classes in your program (and in particular, SomethingElse, can use your Something class).
You can have just one public class per file, and the file must have the same name of the class. But you can have other private classes that just the file class will see. For example:
File Something.java
public class Something {
//Something can access SomethingElse's doSomething method.
private class SomethingElse {
public void doSomething() {
}
}
}
class SomethingToo {
}
File OtherSomething.java
public class OtherSomething {
//OtherSomething cannot access SomethingElse's doSomething method.
//But can access SomethingToo, if they are in the same package
}
You can have multiple classes defined in a same file. However there should only one class defined as public and file name will be that public class name.
In the No code here!!! you can have class variables and methods defined. Your main() is one such example.
In the above file, there are two classes SomethingElse (public) and Something. Now, this is normally done when the non-public class is called internally by the public class. Also, in the above code fragment, SomethingElse seems to be a 'driver' class. In other words, it does not have any functionality/data of its own, but is used to execute (drive) other classes (probably Something in this case)
You can have nested classes, but two separate, public classes are not allowed. Each public class should be in it's own file named the same as the class.
While it's possible to have 2 classes in the same file, its considered bad practice. Besides the decreased readability, it will eventually become difficult to find out where that class declaration actually took place. Plus, if you declare a variable relating to the class, but not the class sharing the .java name, javac will most likely have issues compiling.
If you have to do it, make sure the only place you are using the second class is within the class sharing the .java name. (E.g. only use a Something object within the SomethingElse class). Otherwise, separate all your classes into separate .java files.
Yes, you can have 2 or more classes in single Java file.
The only condition is only one class will contain main method with signature(public static void main(String[] args)).
And only one public class will be there. And with that public class name you can save your file - the file name has to match the name of the public class.
Related
Nowadays we are on writing some core application that is all other application will be relying on. Without further due let me explain the logic with some codes,
We used to have a single java file that was 1000+ lines long and each application was having it as class inside, so when there was a change, each application had to edit the java file inside of it or simply fix one and copy to all. This is hard to implement as much as it is hard to maintain. Then we end-up with creating this as a separate application that is divided to smaller part, which is easy to maintain and also a core maybe a dependency to other application so we fix in one place and all other code applications are fixed too.
I've been thinking for a some great structure for this for a while want to use a builder patter for this as below
TheCore theCore = new TheCore().Builder()
.setSomething("params")
.setSomethingElse(true)
.build();
The problem arises now. Like so, I initialized the object but now I'm having access to that objects public class only. This application actually will have many small classes that has public functions that I don't want them to be static methods that can be called everytime. Instead I want those methods to be called only if TheCore class is initilized like;
// doSomething() will be from another class
theCore.doSomething()
There are some ideas I produced like
someOtherClass.doSomething(theCore)
which is injecting the main object as a parameter but still someOtherClass needs to be initialized or even a static method which doesn't make me feel comfortable and right way to that.
Actually I do not care if initializing TheCore would bring me a super object that includes all other classes inside initialized and ready to be accessed after I initialized TheCore. All I want in this structure to have a maintainable separate app and methods avaiable if only the main object which is TheCore is this circumstances is initialized.
What is to right way to achive it? I see that Java does not allow extending multiple classes even it if does, I'm not sure it that is right way...
Thanks.
After spending significant amount of time of thought I ended up that
// doSomething() will be from another class
theCore.doSomething()
is not suitable since many java classes could possibly have identical method names. So...
// doSomething() will be from another class
theCore.someOtherClass.doSomething()
would be a better approach.
To make it easier to understand I'll have to follow a complex path to explain it which is starting from the package classes first.
Think that I have a package named Tools and a class inside SomeFancyTool
main
└─java
└─com
└─<domainName>
├─Tools
| └─SomeFancyTool.java
└─TheCore.java
Now this SomeFancyTool.java must have a default access level which is actually package level access, because I don't want this classes to be accessed directly;
SomeFancyTool.java
package com.<domainName>.Tools
class SomeFancyTool{
public String someStringMethod(){
return "Some string!";
}
public int someIntMethod(){
return 123;
}
public boolean someBooleanMethod(){
return true;
}
}
So now we have the SomeFancyTool.java class but TheCore.java cannot access it since it is accesible through its Tools package only. At this point I think of an Initializer class that is gonna be in the same package, initialize these private classes and return them with a function when called. So initiliazer class would look like this;
ToolsInitializer.java
package com.<domainName>.Tools
public class ToolsInitializer{
private SomeFancyTool someFancyTool = new SomeFancyTool();
public SomeFancyTool getSomeFancyTool(){
return someFancyTool;
}
}
Since ToolsInitializer.java can initialize all functional private classes inside in Tools package and also can return them as objects to outside of the package scope, still we are not able to use these methods as we cannot import com.<domainName>.SomeFancyTool from TheCore.java because it is package wide accessible. I think here we can benefit from implementation of the java interface. A class that is not functional alone, so no problem even if it is accessed since it's methods will be nothing but declarations.
At this point I'll rename SomeFancyTool.java to SomeFancyToolImplementation.java which it will be implementing the interface and call SomeFancyTool.java to the interface itself.
SomeFancyTool.java (now as an interface)
package com.<domainName>.Tools
public interface SomeFancyTool{
public String someStringMethod();
public int someIntMethod();
public boolean someBooleanMethod();
}
and lets rename prior SomeFancyTool.java and implement the interface
SomeFancyToolImplementation.java (renamed)
package com.<domainName>.Tools
class SomeFancyToolImplementation implements SomeFancyTool{
#override
public String someStringMethod(){
return "Some string!";
}
#override
public int someIntMethod(){
return 123;
}
#override
public boolean someBooleanMethod(){
return true;
}
}
Now our structure has become like this with the final edits;
main
└─java
└─com
└─<domainName>
├─Tools
| ├─SomeFancyTool.java
| ├─SomeFancyToolImplementation.java
| └─ToolsInitializer.java
└─TheCore.java
Finally we can use our TheCore.java class to call all initializer classes with their methods to receive all these private classes inside as an object. This will allow external apps to call and initialize TheCore first to be able to access other methods.
TheCore.java
public class TheCore{
private SomeFancyToolImplementation someFancyTool;
public static class Builder{
private SomeFancyToolImplementation someFancyTool;
public Builder(){
ToolsInitializer toolsInitializer = new ToolsInitializer();
someFancyTool = toolsInitializer.getSomeFancyTool();
}
public Builder setSomeValues(){
//some values that is needed.
return this;
}
public Builder setSomeMoreValues(){
//some values that is needed.
return this;
}
public TheCore build(){
TheCore theCore = new TheCore();
theCore.someFancyTool = someFancyTool;
return theCore;
}
}
}
All Done and it is ready to use. Now the functional package classes and its methods that it relying on if TheCore is initialized or not, cannot be accessed with out TheCore. And simple usage of this Library from a 3rd Party app would simply be;
3rd Party App
TheCore theCore = new TheCore.Builder()
.setSomeValues("Some Values")
.setMoreSomeValues("Some More Values")
.build();
theCore.someFancyTool.someStringMethod();
Note: Note that a the ToolsInitializer.java is still accessible and could be used the get private method without first calling TheCore but we can always set a checker inside getSomeFancyTool() method to throw error if some prerequisites are not satisfied.
I do not still know if this is a functional structural pattern to use or its just some hard thoughts of mine. And don't know if some pattern is already exist that I just could not see yet but this is the solution I end up with.
my annotation processor reads a class like this:
#Foo
public class Bar (){
}
Now I want to generate an inner class Bar$MyGeneratedClass so that at the end I have a class MyGeneratedClass that to the compiler / jvm looks like this:
public class Bar (){
// Generated by annotation processor
public static class MyGeneratedClass () { ... }
}
Is this possible? I think so, I guess I just have to name the generated class Bar$MyGeneratedClass right?
Does anybody know how to generate such a inner class with java poet?
You can use javapoet to create new classes. It's not possible modify existing class with javapoet.
On jvm level there is no such things as inner classes.
So while compiling both classes (the inner and the outer) are transfomed to simulate that effect.
The inner class gets a constructor parameter. With that parameter you need to pass in an instance of the outer class.
As both class types can access private members package private accessors are created.
Especially the second transformation requires you to change the outer class.
So, this is going to sound like an odd question, but I need to know how to get the Class object of a child Object in an inheritance situation for Java reflection.
The situation is this: I'm writing CraftBukkit plugins, Java plugins that work with CraftBukkit, a server-side-only plugin A.P.I. for Minecraft. At the moment, I'm making a plugin that is supposed to be like a "parent" to all of the other plugins I'm writing. It contains large amounts of extra useful Objects and utilities.
One class in the plugin is an Object class called myPlugin that I want all the main classes of all the other plugins to extend. (I know Object names shouldn't start with a lowercase letter, but the lowercase "my" is a trademark with my CraftBukkit plugins.)
One of the things that I want this myPlugin class to do is be able to handle commands to load plugins' data. Therefore, when the command is called, I want the plugin to basically call all of the methods in the plugin's main class that start with "load".
I know how to search through all the Methods in the Class for ones starting with "load" if I can just retrieve the Class, but if I try to call getClass() in the myPlugin class, I believe it's just going to return the myPlugin Class instead of the Class that extends myPlugin.
So, how can I retrieve the Class that extends myPlugin instead of the myPlugin class itself?
EDIT:
I feel that I should mention that I've considered creating an abstract method called mainClass() that will return the Class and making each plugin add this method and return their main class, but this is an ugly fix that I would prefer to avoid.
No it's the subclass name that is returned, consider:
public class ClassOne {
}
public class ClassTwo extends ClassOne {
}
public class Test {
public void someMethod(ClassOne one) {
System.out.println(one.getClass().getName());
}
}
public class Main {
public static void main(String[] args) {
ClassTwo t = new ClassTwo();
Test tst = new Test();
tst.someMethod(t);
}
}
The output is: ClassTwo
Hi I was looking at this syntax from the Android API and found it a bit weird.
java.lang.Object
↳ android.graphics.BitmapFactory.Options
public static class
BitmapFactory.Options
I have never seen a class with a '.' in the middle of it. Why didn't they just call the class 'BitmapFactoryOptions'?
Then I was confused even more because I saw this code in a book
final BitmapFactory.Options options = new BitmapFactory.Options();
BitmapFactory is static yet we are creating an instance of it?
Adding to #dasblinkenlight answer, the code could look like:
public class BitmapFactory {
public static class Options {
}
}
And that's indeed the case, see source code for BitmapFactory.
They did not name the class with a dot in it (that would be illegal). All they did was adding a static inner class called Options - a member class of the BitmapFactory class.
This is a common way of hiding classes inside their outer classes when the class or an interface in question has no meaning on its own, and must be interpreted only in the context of its outer class.
Of course the solution that you suggested (naming the class BitmapFactoryOptions) is perfectly valid as well. However, it gives a false impression that the class can be useful on its own.
Perhaps the most commonly used example of this is the Map.Entry<K,V> interface: map entries have meaning only when there is a map around them, so the nesting is very useful.
Just like any other class variable and class method, there can be class within a class as well. The following example shows all three kinds of class members accessed using the same syntax.
public class Person{
public static long totalPopulation;
public static void calculateAge(Date dob){
}
public static class Address{
}
}
All of these will be accessed in the same way. i.e.,
Person.totalPopulation = 700_000_0000L;
Person.calculateAge(person.getDOB());
Person.Address address = new Person.Address();
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have a file, main.java, and several other files in the same package. Each file is something.class, and I would like to execute them, but I'm having problems locating how to instantiate the class from a something.java file, and then execute it. I am new to java, this is only the second program I've written so please be gentle.
One of the files I'm using is startmessage.java, and here is what I've tried:
Object StartMessage = new StartMessage();
I don't even know if that's correct. Any and all help is very much appreciated.
The class files are the compiled classes.
Source code for Java classes usually go in a file named after themselves.
For example, for your startmessage class, you would use StartMessage.java.
From another file, you can import the class, and then you can instantiate it an object of that type.
For example:
package example;
import StartMessage;
public class Example {
public static void main (String args[]) {
StartMessage startMessage = new StartMessage();
}
}
Case is important.
If your file really is called startmessage.java, and you've compiled it, and you want to create and instance of it, then try:
startmessage sm = new startmessage();
You have to import the Java class you'd like to utilize throughout your code:
package <package_name>
import <location_of_class>
Like so:
package michael;
import parent.child.*; //use any method with *
Useful link on imports and packages: http://www.leepoint.net/notes-java/language/10basics/import.html
In Java, files must be named exactly after the class they contain. In most cases this is a case-sensitive rule. Check it out.
That code segment would compile (assuming you have a StartMessage class with a default constructor), but it's not necessarily correct. Generally, you will want to declare objects in the following fashion:
<type> <name> = new <type>(<args>);
By this design, your code segment would be more correct in the following form:
StartMessage message = new StartMessage();
However, because StartMessage is a subclass of Object, and variables can be named nearly anything, your original code compiles fine.
To execute a precompiled java class (.class) it should have a main method to be executed
and it can be run using command java
http://www2.cs.uic.edu/~sloan/CLASSES/java/
For the second issue, please take a look at the following tutorial:
http://docs.oracle.com/javase/tutorial/java/javaOO/index.html
Well, first thing your file name must be exactly as a class name. For e.g.: If you named the file startmessage.java then you class should look like this:
public class startmessage { }
But it is not the way to name java classes. The proper way is:
public class StartMessage {}
To instantiate a class you should do like this:
StartMessage message = new StartMessage();
If you do like this:
Object message = new StartMessage();
You won't be able to access methods of StartMessage class. The only methods will be available from the Object class.
You can instantiate your class by creating an instance (construct it). For example:
public class MyClass
{
public void myMethod1() {System.out.println("Hello from method 1");}
public void myMethod2() {System.out.println("Hello from method 2");}
}
public class Runner
{
public static void main(String[] args)
{
// declare variable of type MyClass
MyClass myInstance = new MyClass();
// now execute its methods
myInstance.myMethod1();
myInstance.myMethod2();
}
}
This will produce output in the console:
Hello from method 1
Hello from method 2
As per your example in the question, you should use StartMessage instead of Object, e.g.
StartMessage myVariable = new StartMessage();