Why can an instance only be seen by main methods - java

public static void main(String[] args)
{
GUI TestGUI = new GUI();
TestGUI.setVisible(true);
}
public void blahh()
{
TestGUI.setVisible(true);
}
Can not find symbol for TestGUI in blahh, but can be seen in the main method.
How can I access TestGUI from other methods?

This is a scope issue. You could solve this by passing your GUI object to the blahh() method. Currently your blahh method has no way of reaching that variable.
public void blahh(GUI testGui) {
...
}
You can then call this method like this:
blahh(testGui);
Here is some reading you can do on scope, hopefully it will be helpful
Alternatively, you could declare your testGui variable as a field, and it will be accessible from anywhere in the class (make sure to make it static if you must access it in a static method). However, this will offer you less privacy with that variable even though it might seem more convenient.

because you declared TestGUI inside main method as a local varaible to a method , declare it as a class property
static GUI TestGUI;
public static void main(String[] args)
{
Test = new GUI();
TestGUI.setVisible(true);
}
public void blahh()
{
TestGUI.setVisible(true);
}

Related

In java constructor and main which one will execute first?

Basically which one will execute first the main method or the constructor?
public class ConstructorExp {
public ConstructorExp() {
System.out.println("Ctt");
}
public static void main(String[] args) {
System.out.println("Inside Main Methos");
System.out.println("Main");
}
}
The main method will always be excecuted first, because it is a special static method that will be called from Java itself to start an application.
For more about the main method please read Java main() Method Explained for example.
Constructors will be created on object creation - in your case no object creation happens - so the constructor will never be executed.
You could modify your example to also execute the constructor:
public class ConstructorExp {
public ConstructorExp() {
System.out.println("Ctt");
}
public static void main(String[] args) {
System.out.println("Inside Main Methos");
ConstructorExp example = new ConstructorExp();
System.out.println("Main");
}
}
Be carefully, because the example object is never used the constructor call might be eliminated by some kind of optimization depending on the compiler you are using.

Should GUI object be declared in a separate java class to be accessible

I would like to access one variable that is a part of my GUI class. Should I instantiate my GUI class outside of that GUI class? Right now it is instantiated inside of main which I believe makes it inaccessible for me.
So is the best way to access variables in this class to instantiate this object in a different class and in that class create getters and setters for it?
public class NormalDistributionUI extends JFrame {
public static void main(String args[]) {
new NormalDistributionUI().setVisible(true);
}
}
Should it be like e.g.
public class Main {
static NormalDistributionUI ndUI;
public NormalDistributionUI getndUI() {
return ndUI;
}
public static void main(String args[]){
ndUI = new NormalDistributionUI();
}
}
EDIT: a different idea
public class NormalDistributionUI extends JFrame {
static NormalDistributionUI ndUI;
public static void main(String args[]) {
ndUI = new NormalDistributionUI()
ndUI.setVisible(true);
}
}
Does that make more sense than creating a separate class?
It depends on what you want. The second alternative would work as well, assuming that you called the method setVisible somewhere else.
The difference between the two of them is that in the second case the GUI object will be named and, hence, accessible afterwards. In the first case, it is anonymous.
You don't need a whole separate class. The first one is fine. If you want to manipulate the NormalDistributionUI object, you can use a local variable.
public class NormalDistributionUI extends JFrame {
public static void main(String args[]) {
NormalDistributionUI ndUI = new NormalDistributionUI();
ndUI.setSomeProperty(foobar);
ndUI.setVisible(true);
}
}

Why are we allowed to have a final main method in java?

Can anyone tell me the use of making main method as final in java.
while this is allowed in java
public static final void main(String[] args) {
}
I dont see any use of making it final. anyways it is static so we can not override it.
Adding final to a static method can actually make a difference. Consider the following code:
class A {
public static void main(String[] args) {
System.out.println("A");
}
}
class B extends A {
public static void main(String[] args) {
System.out.println("B");
}
}
class C extends B {
}
public class Test {
public static void main(String[] args) {
C.main(args); // Will invoke B.main
}
}
Adding final to A.main would prevent accidental hiding of A.main. In other words, adding final to A.main guarantees that B.main is not allowed, and that C.main therefore prints "A" as opposed to for instance "B".
Why are we allowed to have a final main method in java?
Beside the above corner case, adding final to a static method doesn't make much difference, so I don't see a big point in adding a rule for disallowing it.
More information available here: Behaviour of final static method

non-static variable newJourney cannot be referenced from a static context

Ive trying to build some code and keep running into this error. Ive tried ways around it but it then messes with the execution of methods within Journey.
Ive looked at other threads but cant seem to find an answer.
class Main{
private Journey newJourney;
public static void main(String[] args){
startStation.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent event){
if(event.getStateChange()==ItemEvent.SELECTED){
String selectedItem = startStation.getSelectedItem().toString();
newJourney = new Journey();
newJourney.setStart(selectedItem);
}
}
}
);
Obviously ommited some code but thats the main just of things.
Any help is appreciated and the error im recieveing is
Main.java:102: non-static variable newJourney cannot be referenced from a static context
newJourney.setStart(selectedItem);
^
The error says it all. newJourney is not a static variable where main is a static method. This means main cannot access it. This means the following code will not work
private Journey newJourney;
you would need
private static Journey newJourney;
You should declare your object as a sataic one as following:
private static Journey newJourney;
Because you are using this object in a non-static way, It must be a static one
You may want to adopt the following paradigm, in which you create a new object for the class that your static Main method is in, and then do all your work from that object.
class Main{
private static final Main me;
private Journey newJourney;
public static void main(String[] args){
me = new Main();
me.doWork(args);
}
private void doWork(String[] args) {
startStation.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent event){
if(event.getStateChange()==ItemEvent.SELECTED){
String selectedItem = startStation.getSelectedItem().toString();
newJourney = new Journey();
newJourney.setStart(selectedItem);
}
}
}
);
}
newJourney is not static, you are trying to access into static methods.
As a Java concept, an object's state can not be changed inside static methods.

public static void main () access non static variable

It is said that non-static variables cannot be used in a static method. But public static void main does. How is that?
No, it doesn't.
public class A {
int a = 2;
public static void main(String[] args) {
System.out.println(a); // won't compile!!
}
}
but
public class A {
static int a = 2;
public static void main(String[] args) {
System.out.println(a); // this works!
}
}
or if you instantiate A
public class A {
int a = 2;
public static void main(String[] args) {
A myA = new A();
System.out.println(myA.a); // this works too!
}
}
Also
public class A {
public static void main(String[] args) {
int a = 2;
System.out.println(a); // this works too!
}
}
will work, since a is a local variable here, and not an instance variable. A method local variable is always reachable during the execution of the method, regardless of if the method is static or not.
Yes, the main method may access non-static variables, but only indirectly through actual instances.
Example:
public class Main {
public static void main(String[] args) {
Example ex = new Example();
ex.variable = 5;
}
}
class Example {
public int variable;
}
What people mean when they say "non-static variables cannot be used in a static method" is that non-static members of the same class can't be directly accessed (as shown in Keppils answer for instance).
Related question:
Accessing non-static members through the main method in Java
Update:
When talking about non-static variables one implicitly means member variables. (Since local variables can't possible have a static modifier anyway.)
In the code
public class A {
public static void main(String[] args) {
int a = 2;
System.out.println(a); // this works!
}
}
you're declaring a local variable (which typically is not referred to as non-static even though it doesn't have a static modifier).
The main method does not have access to non-static members either.
final public class Demo
{
private String instanceVariable;
private static String staticVariable;
public String instanceMethod()
{
return "instance";
}
public static String staticMethod()
{
return "static";
}
public static void main(String[] args)
{
System.out.println(staticVariable); // ok
System.out.println(Demo.staticMethod()); // ok
System.out.println(new Demo().instanceMethod()); // ok
System.out.println(new Demo().instanceVariable); // ok
System.out.println(Demo.instanceMethod()); // wrong
System.out.println(instanceVariable); // wrong
}
}
This is because by default when you call a method or variable it is really accessing the this.method() or this.variable. But in the main() method or any other static method(), no "this" objects has yet been created.
In this sense, the static method is not a part of the object instance of the class that contains it. This is the idea behind utility classes.
To call any non-static method or variable in a static context, you need to first construct the object with a constructor or a factory like your would anywhere outside of the class.
More depth:
Basically it's a flaw in the design of Java IMO which allows static members (methods and fields) to be referenced as if they were instance members. This can be very confusing in code like this:
Thread newThread = new Thread(runnable);
newThread.start();
newThread.sleep(1000);
That looks like it's sending the new thread to sleep, but it actually compiles down into code like this:
Thread newThread = new Thread(runnable);
newThread.start();
Thread.sleep(1000);
because sleep is a static method which only ever makes the current thread sleep.
Indeed, the variable isn't even checked for non-nullity (any more; it used to be, I believe):
Thread t = null;
t.sleep(1000);
Some IDEs can be configured to issue a warning or error for code like this - you shouldn't do it, as it hurts readability. (This is one of the flaws which was corrected by C#...)
**Here you can see table that clear the access of static and non-static data members in static and non-static methods. **
You can create non-static references in static methods like :
static void method() {
A a = new A();
}
Same thing we do in case of public static void main(String[] args) method
public class XYZ
{
int i=0;
public static void increament()
{
i++;
}
}
public class M
{
public static void main(String[] args)
{
XYZ o1=new XYZ();
XYZ o2=new XYZ();
o1.increament();
XYZ.increament(); //system wont be able to know i belongs to which object
//as its increament method(static method)can be called using class name system
//will be confused changes belongs to which object.
}
}

Categories