public class MainForm {
String varpass = "This is a string that has to be passed.";
public String t1(){
String text = "This is a non-static method being called.";
return text;
}
public static String t2(){
String text = "This is a static method being called.";
return text;
}
public void t3(){
System.out.println("This is a non-static void method and cannot return.");
}
public static void t4(){
System.out.println("This is a static void method and cannot return.");
}
public void place1 (){
//=======================================Method calls from another class========================================
//Calls from another class. It is non-static and thus requires it to be instantiated. EG. class var = new class();
Methods call = new Methods();
System.out.println(call.t1());
//Calls from another class. It is non-static void and thus requires it to be instantiated and be called straight.
call.t3();
//Calls from another class. It is static and thus does not require it to be instantiated. EG. class var = new class();
System.out.println(Methods.t2());
//Calls from another class. It is static void and thus does not require it to be instantiated.
Methods.t4();
//Trying to call a variable that was sent.
Methods.getvar(varpass);
call.getvar(varpass);
//=======================================Method calls from current class========================================
MainForm mcall = new MainForm();
//Calls from within the same class. It is static and thus does not require it to be instantiated. EG. class var = new class();
System.out.println(mcall.t1());
mcall.t3();
System.out.println(t2());
t4();
}
public static void main(String[] args) {
MainForm place = new MainForm();
place.place1();
}
}
public class Methods {
String var1 = "This is a public String variable";
String getVar = "Initial";
public String t1(){
String text = "This is a non-static method being called.";
return text;
}
public static String t2(){
String text = "This is a static method being called.";
return text;
}
public void t3(){
System.out.println("This is a non-static void method and cannot return.");
}
public static void t4(){
System.out.println("This is a static void method and cannot return.");
}
public void getvar(String varsent){
String msg = "getver() Variables are varsent("+varsent+"), getVar("+getVar+"), getVar(";
getVar = varsent;
msg = msg + getVar+")";
System.out.println(msg);
}
}
Here is the errors below
Methods.getvar(varpass);
call.getvar(varpass);
top one is giving non-static cannot be referenced from a static context
bottom one is saying cannot resolve method 'println(void)'
You can tell im using this as practice to call methods.
Here im trying to pass a variable varpass that contains a string. I want it pass that variable to getvar in Methods. in that getvar it takes a variable in Methods displays it before altering it then again after alter.
Im trying to understand how this works. Any insight would be appreciated.
This line
Methods.getvar(varpass);
is a static call. You try to call the static Method getvar from your Methods class. This method however is not static and therefor requires an instance of Method.
This line
call.getvar(varpass);
works fine. It in fact is the solution to the first line, where you reffere a non-static method from a static context
You cannot refer to a non-static variable/field from a static method, because a non-static field may vary between instances of a class. To solve it, make varpass static:
static String varpass = "This is a string that has to be passed.";
The second error results from the definition of getvar:
public void getvar(String varsent);
Since it does not return anything, it cannot be used in a System.out.println() as there is no definition of println accepting void (It doesn't know what to print).
Also, Methods.getvar(varpass) should be Methods.getvar(MainForm.varpass), because there is no local variable with that name.
Related
public class StaticFinalExample {
static String str;
public void StaticFinalExample() {
System.out.println("In Constr");
str = "H";
}
public static void main(String[] args) {
StaticFinalExample t = new StaticFinalExample();
System.out.println(str);
}
}
In above example the output is null.
Why was not the constructor called?
Constructors don't have a return type. There shouldn't be void in your StaticFinalExample() method, if that's your constructor.
Avoid using class name as a method name, it's ambiguous. When we notice any name having same value as class, our mind reads as a class name not as actual usage (method name in your case).
It's not a good practice. It does not mean you can not use method name as class name, but you should avoid using same name.
I have the following global variable of String type.
static public String rev="hello"
I can read it without any issue from an object of another class. Is there anyway I can update it with another string from an object of another class? I know Java string is immutable. I tried with the following way using StringBuilder:
static public StringBuilder rev=new StringBuilder("hello");
static public void setRev(StringBuilder s)
{
rev=rev.delete(0,rev.length());
rev.append(s);
}
From another class:
MainActivity.setRev(stringBuilderVar);
But it did not work.
The syntax for updating a field is the same for static and non-static fields. Simply use an assignment statement:
class Global {
public static String greeting;
}
public class Other {
public static void main(String[] args) {
String newGreeting = "hello";
Global.greeting = newGreeting;
}
}
That said, once your programs get bigger, you'll likely want to use non-static fields instead.
Hi after a long time i am learning java , i have a confusion in calling the method without the help of the object.
public class VariablesInJava {
int instanceField=5;
static String staticField = "apple";
public void method() {
final String localVariable = "Initial Value";
System.out.println(localVariable);
}
public static void main(String args[]) {
VariablesInJava obj = new VariablesInJava();
System.out.println(obj.instanceField);
System.out.println(obj.staticField);
System.out.println(VariablesInJava.staticField);
System.out.println(new VariablesInJava().instanceField);
obj.method();
}
}
How can i call the method() without the help of object ?
You can create a static method and call the method without creating an object of that class.
Since main method is a static method you either need to create an object of class VariablesInJava and then call it or make the "method" static.
Do this :
public static void method()
Now you can simply call method() without creating an object.
Hope that helps.
/**
* A preference change listener to resynchronize a contact list
*
*/
private static Preference.OnPreferenceClickListener resynchronizeContactsListener = new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
new AlertDialog() {
}
}
}
In a code snippet such as the above, I need to call a non-static method, or create an AlertDialog(). Both of which I am having difficulty doing since the listener is a static method.
For example, the AlertDialog.Builder() constructor requires an android context object to be created, but since the method is static there is no context. I considered passing in the context as a parameter, however I am not sure where to do so without damaging the fact that I am overriding a method.
Thanks in advance
You can implement the Preference.OnPreferenceClickListener into your own class statically and initialise it from your activity code when ready. (I am assuming that you need the listener object to be static for some reason, you may do away with that!)
private static MyPrefListener myPrefListener = null;
private static class MyPrefListener implements Preference.OnPreferenceClickListener {
private Context mContext;
public MyPrefListener(Context context) {
this.mContext = context;
}
#Override
public boolean onPreferenceClick(Preference preference) {
//USE mContext as the context object here
return false;
}
}
Then in your Activity code, do this:
myPrefListener = new MyPrefListener(this);
I hope the structure of the code is clear.
Basically, A static method cannot call a non-static method, but we can use a reference, which include a non-static method to the static method.
public class StaticMethodTest{
void NonStaticMethod(){
System.out.println("This is a non-sataic method.");
}
static void StaticMethod(StaticMethodTest s){
System.out.println("This is a static method.");
s.NonStaticMethod();
}
public static void main(String[] args) {
StaticMethodTest sObj=new StaticMethodTest();
StaticMethod(sObj);
}}
This is a java example, I think you can use this way to create a object, and use it reference into the static method.
Hope it can help you.
Basically, A static method cannot call a non-static method, but we can use a reference, which include a non-static method to the static method.
public class StaticMethodTest{
void NonStaticMethod(){
System.out.println("This is a non-sataic method.");
}
static void StaticMethod(StaticMethodTest s){
System.out.println("This is a static method.");
s.NonStaticMethod();
}
public static void main(String[] args) {
StaticMethodTest sObj=new StaticMethodTest();
StaticMethod(sObj);
}}
This is a java example, I think you can use this way to create a object, and use it reference into the static method. Hope it can help you.
Just remove the static keyword from your declaration.
A class or interface (note not the actual instantiated object, simply the class definition) is declared static when it's an inner class but has no reference to it's containing class. EG
public class Foo {
public static class Bar {
}
}
Bar cannot reference any of the state of Foo and can be instantiated independently with new Foo.Bar().
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.
}
}