I have two packages inside my project, a and b.
a is my "main class" that runs when the program runs but I need to make b run from a (if that makes sense).
I'm sure its something along the lines of PackageB.BMain but I'm not sure.
Edit:
Okay so I've learned a few new things, to start my main project is RevIRC, inside that I have two packages, MainChat and RevIRC, now when I run the program RevIRC is ran, I need to make Mainchat run when RevIRC is ran.
Like I said before I'm sure its something along the lines of RevIRC.MainChat.ChatMain() but I can't seem to figure it out.
You have 2 options:
Either create a new instance of B from A, like so: PackageB.BMain b = new PackageB.BMain();
Access the methods in BMain in a static way like so: PackageB.BMain.someMethod();`
Note that you can use either of these exclusively or mix them up together, however, it all depends on how you have written your BMain class.
So for instance:
package PackageB
public class BMain
{
public BMain()
{ }
public void foo()
{
System.out.println("This is not a static method. It requires a new instance of BMain to be created for it to be called");
}
public static void bar()
{
System.out.println("This is a static method. It can be accessed directly without the need of creating an instance of BMain");
}
}
Then in your main class (the class which has the main method):
package PackageA
public class AMain
{
public static void main(String[] args)
{
PackageB.BMain.bar();
PackageB.BMain bInstance = new PackageB.BMain();
bInstance.foo();
}
}
If you have two main methods it will either run from A or B. The JVM will choose the first main method it sees IIRC.
Have a standalone class that will have main. And create your classes there.. ?
import a.Class1;
import b.Class2;
public class MainController
{
public static void main(String args[])
{
Class1 class1 = new Class1() ;
Class2 class2 = new Class2() ;
//Both class no start at the "same" time.
}
}
if i am not wrong you want to run main method of class B from class A.
That you can call using B.main(arg[]);
eg :
package a;
public class A
{
public static void main(String[] args)
{
System.out.println("This is main method of class A");
B.main(null);
/*pass any args if you want or simply set null arg*/
}
}
package b;
public class B
{
public static void main(String[] args)
{
System.out.println("This is main method of class B");
}
}
i hope this simple example will clear your doubt.
you can refer to link which contains Java tutorial for beginners.
Related
I'm trying to view the elements of an ArrayList in a different class but it shows that there is nothing. In the other class, you can see the element in the ArrayList though.
Here are the codes.
First class
import java.util.ArrayList;
public class Test {
ArrayList<String> inventory = new ArrayList<String>();
public void test() {
inventory.add("item");
}
public void check() {
System.out.println(inventory);
}
}
Second class
import java.util.ArrayList;
public class Test2 {
Test testObj = new Test();
public void test2() {
System.out.println(testObj.inventory);
}
}
Main class
public class Main {
public static void main(String[] args) {
Test testObj = new Test();
Test2 test2Obj = new Test2();
testObj.test();
testObj.check();
test2Obj.test2();
}
}
Output
[item]
[]
In java Class level variables are Object associated until unless they are not declared static.
By means of Object associated is that when a object is initialized with new keyword in Java all Object will be having it's own memory and own class variables.
In your case inside main method when you create a Object of Test class and when you create a another test class object inside Test2 class, both will be totally independent of each other. And both will be having their own memory and own variables.
If you want that to get the updates of inventory variables from first object to be available in another object you need to declare it as static and should be initialized inside static block. Static variables are shared across all objects of class. As below:
static ArrayList<String> inventory;
static {
inventory = new ArrayList<String>();
}
In your main method, you call the method that handles adding operation yet you do not call any add methods in the second class and in your main method.
testObj.test();
testObj.check();
This one shows that you add an item into the arraylist and show it. But in the second class you do not add anything but calling it. Therefore there is no way to show any element from that method. What has should be done is that you just need to call the adding method inside of the second class and then try to use the display method.
You didn't call test() method in Test2 class.
To make it work change the Test2 class as follows.
import java.util.ArrayList;
public class Test2 {
Test testObj = new Test();
public void test2() {
testObj.test();
System.out.println(testObj.inventory);
}
}
I've been flustered over trying to figure out how to call a method from an instance of a class from a different class. For example:
public class Test1
{
public static void makeSomeInst()
{
Test1 inst = new Test1();
inst.fireTest();
}
public void fireTest()
{
System.out.println("fireTest");
}
public Test1()
{
}
}
no problem with understanding the above, but what If I want to do something to inst from a class called Test2, how would I do that? The below example doesn't work:
public class Test2
{
public static void main(String[] args)
{
Test1.makeSomeInst();
inst.fireTest();
}
}
And just to be extra clear, I get that I can call static references without instantiating, but I just want to know, in this specific case
What is the syntax to reference the test1 object called inst from the Test2 class?
what If I want to do something to inst from a class called Test2, how would I do that?
First of all you have to teach the Test2 class what Test1 is.
public class Test2
{
public doSomething()
{
inst.fireTest();
}
public Test2(Test1 inst)
{
this.inst = inst;
}
private Test1 inst;
}
Then teach the inst2 object what inst is.
public class Test1
{
public static void main(String[] args)
{
Test1 inst = new Test1();
Test2 inst2 = new Test2(inst); // <- new code
inst2.doSomething(); // <- new code
}
public void fireTest()
{
System.out.println("fireTest");
}
public Test1()
{
}
}
You only need one main to start the show. Flow of control can still pass through other objects. But at this point I wouldn't call these independent tests. I only used that name to match your code.
What you're looking at is something called reference passing. The fancy term for it is Pure Dependency Injection*. The basic pattern is to build an object graph in main. Once that's built call one method on one object to start the whole thing ticking.
In main you build every object that will live as long as your program does. What you wont find built here are objects that are born later, such as timestamps. A good rule of thumb is to build each of these long lived objects before doing any real work. Since they know about each other they can pass flow of control back and forth between them. There's a lot of power there and if not used well it can get confusing. Look into Architectural Patterns to help keep that simple.
The principle followed here is to separate use from construction. Following that allows you to easily change your mind about what talks to what in one place. It's nice when a design change doesn't force you to rewrite everything.
You have to save your instance somewhere.
If Test1 should be a singleton, you can do:
public class Test1
{
private static Test1 instance;
public static Test1 getInstance()
{
return instance == null ? instance = new Test1() : instance;
}
public static void main(String[] args)
{
Test1 inst = getInstance();
inst.fireTest();
}
public void fireTest()
{
System.out.println("fireTest");
}
}
and in Test2:
public class Test2
{
public static void main(String[] args)
{
Test1.getInstance().fireTest();
}
}
//Edit
As I just learned from #Thomas S. comment, singletons are not a good solution.
See #candied_orange's answer for a better implementation.
//: innerclasses/TestBed.java
// Putting test code in a nested class.
// {main: TestBed$Tester}
public class TestBed {
public void f() { System.out.println("f()"); }
public static class Tester {
public static void main(String[] args) {
TestBed t = new TestBed();
t.f();
}
}
} /* Output:
f()
*///:~
I am studying "Think in Java". I am just wondering why the above code doesn't work which should be a way to test each class, and can be removed by deleting TestBed$Tester.class file.
The error msg instructs there should be a public static void main(String[] args) in TestBed class as program entry.
java compile version: javac 1.7.0_40
The main method must be in the public top-level class. That is the one with the same name as the java-file. Here, that's the TestBed-class.
The current main method is in an inner class (namely TestBed$Tester), and can't be used to start a program.
EDIT: I may have been wrong. I took a look in the book you mentioned, and it looks like you're able to run the inner class from the Command Promt by writing:
java TestBed$Tester
This question already has an answer here:
Import custom Java class
(1 answer)
Closed 9 years ago.
I am a beginner at java, I used to code in C++ and there when using classes I used to define them in separate files and then include those classes in my main file.
I'm trying to learn threads for socket programming so I can open multiple server ports as threads and accept multiple clients. I know that in Java the file name should be the same as the class name (correct me if i am wrong). This is what I am trying to do:
main.java
include derived.java;
class main1
{
main1()
{
System.out.println("Constructor of main1 class.");
}
void main1_method()
{
System.out.println("method of main 1 class");
}
public static void main(String[] args)
{
main1 my = new main1();
Derived derivedThread = new Derived();
derivedThread.start();
}
}
derived.java
public class derived extends Thread
{
public void run()
{
System.out.println("starting a new thread");
}
}
How can I create a derived class object in main and include it in my main1.java file?
I think I do not fully understand how classes work in Java and what classpath has to be used with it. I have a deadline for my networking project and I am very behind so please help me!
Delete your files and try this, this is how it should look in Java:
Derived class: Derived.java
public class Derived extends Thread {
public void run() {
System.out.println("starting a new thread");
}
}
Main1 class: Main1.java
public class Main1 {
public Main1() {
System.out.println("Constructor of main1 class.");
}
void main1_method() {
System.out.println("method of main 1 class");
}
public static void main(String[] args) {
Main1 my = new Main1();
Derived derivedThread = new Derived();
derivedThread.start();
}
}
Note:
1) Class names are always capitalized, and you are right, the filename must be the same. In addition, the constructor and any calls to the constructor must be capitalized.
2) If you put classes in the same package, you don't need to import them. If you have multiple packages, you would import like so: import packageName.className;. No need for .java at the end, strictly the class name. You can also have nested packages, so you might see things like: import java.util.ArrayList;. This would be using ArrayList class, found in the util package, which is in the java package (built in). You shouldn't have to worry much about making nested packages on smaller projects, but that's the concept.
3) Notice I added the public modifier to Main1 and it's constructor. It is good practice to give a modifier to class names and methods, as well as class variables. See this SO Question for information about modifiers. For a beginner, you should mostly only be concerned with public and private.
I hope that helps, and good luck with your Java studies.
No need to use this include derived.java; .Use import if the derived class exist in different package.The class Derived is different while calling and declaring.
class main1 // Class name must start with Uppercase
{
public static void main(String[] args)
{
main1 my = new main1(); // Can be remove
Derived derivedThread = new Derived();
derivedThread.start();
}
}
public class derived extends Thread // Change derived to Derived
--------------------^
{
public void run()
{
System.out.println("starting a new thread");
}
}
I have remove constructor and one method which is not used.
I am working on a project, and I have come across something i do not fully understand yet.
Every time I like to call a method from another class, or use a variable from a jform my netbeans says that I need to make it "static". Now I understand what static means, and I have created objects from the class that I use methods from, but even then netbeans says that I need to make the object static before i can use it in the MAIN() method. Even the jform variables like comboboxes.
can somebody please explain this?
thanks in advance!
EDIT:
this is some code from my project. It's very small but it should clarify the problem:
the Mainclass:
public class SpeeloTheek {
/**
* #param args the command line arguments
*/
public static Controller MainController = new Controller();
public static SummaryScreen MainSummaryScreen = new SummaryScreen();
public static void main(String[] args) {
// TODO code application logic here
MainSummaryScreen.setVisible(true);
MainController.SetFullScreen(MainSummaryScreen);
MainController.ComboBoxItemSelected(SummaryScreen.choiceBox);
}
the controller class:
package speelotheek;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class Controller {
//Method to make JFrame fullscreen//
public void SetFullScreen(JFrame frameToUse) {
frameToUse.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
public void ComboBoxItemSelected(final JComboBox comboBoxToUse) {
comboBoxToUse.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
WhichSummary(comboBoxToUse);
}
}
});
}
public void WhichSummary(JComboBox comboBoxToUse) {
System.out.println(comboBoxToUse.getSelectedItem());
}
}
EDIT2:
Thanks all :) I found the problem. I instantiated the class in the main method instead above the main method and it worked :)
In order to call non-static members of a class you need to instantiate an object.
Example:
Foo myObject = new Foo(); // myObject is an object of class Foo
Foo.callToStaticMember(); // static members can be called using the class name
myObject.callToNonStaticMember(); // non-static members require an object of the class
This is because your main method is a static method.
From a static method you can't call the non static method's or variablen.
You need to change your main method to a constructor.
Then this code will be executed when you make an new instance of this class.
If you're using Netbeans GUI Builder, what you want to do is work from the constructor, instead of the main method
public NewJFrame() {
initComponent();
jComboBox1.addItem("Hello");
// do everything with your components here
}
All the objects declared by the GUI Builder are non-static. They're not meant to be accessed from the main.
if you are trying to access non-static methods from the main method. It would not work. The reason being, that static methods/variables do not belong to the instance of the class.
If you do need to access a non static method in your main method of another class. the only way to do it is through the instance of the class.
So, you would need to say
MyClass object = new MyClass();
object.aMethod();
EDIT
Do you want your application to be all static? Basically, static would mean that it will have only one memory location. So, for eg: if a user selects a radio button on one screen. it modifies the value in your code, and another user selects another radio button, it will overwrite the previous user's value.
What you do need to do is something like this.
public static void main(String[] args) {
// TODO code application logic here
Application appObject = new Application();
appObject.setController(new Controller());
appObject.setSummaryScreen(new SummaryScreen()); // Or pass these values through a constructor. Setters are just one way to do it. Or better yet, use Spring DI.
appObject.performAction();
}
public Class Application {
public Controller MainController ;
public SummaryScreen MainSummaryScreen ;
.... getters and setters of these instance variables.
public performAction(){
MainSummaryScreen.setVisible(true);
MainController.SetFullScreen(MainSummaryScreen);
MainController.ComboBoxItemSelected(SummaryScreen.choiceBox);
}
}
While you are working within the main method, which is static
public static void main(String[] args){
}
you can only call static elements, such classes, enum or static methods.
If you want to call a method member of a class from your main method, you have two options
Make the method static
class ClassA{
public static void methodOne(){
}
}
public static void main(String[] args){
ClassA.methodOne();
}
Instantiate the class in your main and call the non-static method.
class ClassA{
public void methodOne(){
}
}
public static void main(String[] args){
ClassA classA = new ClassA();
classA.methodOne();
}
Advice
You have to take care while using static methods, because they share its memory.
when you create a new class ClassA classA = new ClassA();, for each new class you create, it stores its own non-shared memory variables, but when you use static methods, they share the memory which could be dangerous.