Scope of statics and key word "this" in java [duplicate] - java

This question already has answers here:
Why can't we use 'this' keyword in a static method
(9 answers)
Closed 5 years ago.
I have a question about this fragment of code :
public class Inner {
static int a;
public static void main(String[] args) {
a = 0;
}
public static void g() {
this.a = 0;
}
}
`
Why we can't use "this.a" in static method, but we can use "a" without "this"?
Photo of compilation error: https://www.dropbox.com/s/5q6y3ldsf37p0h3/%D0%97%D0%BD%D1%96%D0%BC%D0%BE%D0%BA%20%D0%B5%D0%BA%D1%80%D0%B0%D0%BD%D0%B0%202017-05-27%2017.28.34.png?dl=0

Because this points to an instance of the class, in the static method you don't have an instance.
The this keyword refers to the current instance of the class. Static member functions do not have a this pointer
You'll notice the definition of a static member is
Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object
Which is why this has nothing to point to.

Related

Method Calls Not Working [duplicate]

This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 4 years ago.
The method calls at the end of the main method are giving me an error saying "non-static method cannot be referenced from a static context" I'm not sure what I'm doing wrong in the method call.
public static void main(String[] args)
{
ArrayList<Candidate> voteCount = new ArrayList<Candidate>();
//add objects to voteCount
printListResults(voteCount);
totalListVotes(voteCount);
printListTable(voteCount);
}
public void printListResults(ArrayList<Candidate> election)
{
//some code
}
public int totalListVotes(ArrayList<Candidate> election)
{
//some code
}
public void printListTable(ArrayList<Candidate> election)
{
//some code
}
You simply need to declare these methods as static
public static void printListResults(ArrayList<Candidate> election) {
//some code
}
public static int totalListVotes(ArrayList<Candidate> election) {
//some code
}
public static void printListTable(ArrayList<Candidate> election) {
//some code
}
An alternative approach would be to instantiate an object of your class, as pointed out in the answer from JoschJava. Either way will work. Which approach you choose is partly a matter of taste and partly depends upon the needs of your application (which is beyond the scope of this question).
The problem is that you're trying to call a class method from a static method. You need to instantiate your class:
YourClass classObj = new YourClass();
classObj.printListResults(voteCount);

Does static variable inherited? [duplicate]

This question already has answers here:
Are static variables inherited
(4 answers)
Closed 4 years ago.
We know that in java static variable are not inherited. But in below code I am not getting any error as I want to initialize the static variable in child class.
class s
{
static int x;
}
class aaa extends s
{
void fun()
{
x=2;
System.out.println(x);
}
public static void main(String args[])
{
aaa w=new aaa();
w.fun();
}
}
static members are most definitely accessible from subclasses, as your example shows. You cannot override them, of course, but you could hide them.

can public static final string variables be overridien in sub-classes? [duplicate]

This question already has answers here:
How to inherit static field and change it's value?
(4 answers)
Closed 7 years ago.
Here is the sample program:
public class Base {
public static final String FOO = "foo";
public static void main(String[] args) {
Base b = new Base();
Sub s = new Sub();
System.out.print(Base.FOO);
System.out.print(Sub.FOO);
System.out.print(b.FOO);
System.out.print(s.FOO);
System.out.print(((Base)s).FOO);
}
}
class Sub extends Base {
public static final String FOO="bar";
}
When I execute this it's printing foobarfoobarfoo.
Since String FOO is declared as public static final, my understanding is its value cannot be changed anymore. But in the subclass Sub, the value is being changed to bar.
Shouldn't the program throw a compilation error?
Why is it printing foobarfoobarfoo?
Static variables are not inherited, they belong to the class, that's why they are static. The subclasses can have static fields with the same, though.

error when calling a void function [duplicate]

This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Cannot make a static reference to the non-static method
(8 answers)
Closed 8 years ago.
public class Makakiesmarkou {
void swap(int i, int j, int[] arr) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
public void MySort(int[] T)
{
for(int m=0; m<T.length-1; m++)
{
int j=m;
for(int k=m+1; m<T.length-1; k++)
{
if(T[k]<T[j])
j=k;
}
swap(T[j], T[m], T);
}
}
public static void main(String[] args) {
int[] pin= new int[50];
MySort(pin);
System.out.println(Arrays.toString(pin));
}
}
the error when i call MySort in the main class is "non static method MySort[int[]] cannot be referenced from a static context"
what am i doing wrong?
You can either do what Salah said, or you can instantiate your class and call MySort on that:
public static void main(String[] args) {
int[] pin= new int[50];
Makakiesmarkou m = new Makakiesmarkou();
m.MySort(pin);
System.out.println(Arrays.toString(pin));
}
You need to change the declaration of your method to be static like:
public static void MySort(int[] T)
static variable initialized when class is loaded into JVM on the other hand instance variable has different value for each instances and they get created when instance of an object is created either by using new() operator or using reflection like Class.newInstance().
So if you try to access a non static variable without any instance compiler will complain because those variables are not yet created and they don't have any existence until an instance is created and they are associated with any instance. So in my opinion only reason which make sense to disallow non static or instance variable inside static context is non existence of instance.
Read more here

Can not make static reference to non static method? [duplicate]

This question already has answers here:
Static Classes In Java
(14 answers)
Closed 3 years ago.
So, in short. I have two classes.
package rpg;
public class Engine {
public void main(String args[]) {
Start.gameStart();
System.out.println(menuResult);
}
}
and
package rpg;
public class Start {
int menuResult = 3;
public int gameStart()
{
return menuResult;
}
public int getMenuResult()
{
return Start.menuResult;
}
}
It keeps throwing up the error 'Cannot make static reference to non-static method gameStart()'.
I'm sure I'm missing something simple, but can't find it.
Thanks!
You need to create instance of Start class and call gameStart() method on that instance because gameStart() is instance method not static method.
public void main(String args[]) {
new Start().gameStart();
..................
}
Only static methods can be accessed by using class name as perfix.
public int gameStart() <--- Instance method not static method
call it on instance
Start start = new Start();
start.gameStart();
So finally your classes should look like below
public static void main(String args[]) {
Start start = new Start();
start.gameStart();
System.out.println(start.getMenuResult());
}
public class Start {
private int menuResult = 3;
public int gameStart() {
return this.menuResult;//Don't know why there are two methods
}
public int getMenuResult() {
return this.menuResult;
}
}
first of all the main method should be
public static void main(String args[]) {
}
I assume you can have multiple games, and hence you should be able to start multiple instances so you should create a non static class that can be created and then actions performed against.
to answer your original question, you need to have a static variable that have static getters and setters..
public class Start {
private static int menuResult = 3;
public static int gameStart()
{
return menuResult;
}
public static int getMenuResult()
{
return Start.menuResult;
}
If you need the method to be static, just add the keyword static in the function definition. That would get rid of the error. But if you want to keep the class Start the way it is, then you should create an instance of Start in the main function and then call the method. Hope that helps!
you are trying to invoke a method on its class name. you should be creating a new object and invoke its method
public void main(String args[]) {
new Start().gameStart();
System.out.println(menuResult);
}
Start.gameStart() refers to a method which would be public static int gameStart() because Start is the class and not an instance of the object.
If you declare a method on an object, you need to apply it to instance of the object and not its class.
When to use static or instanciated methods ?
instanciated : whenever you need to apply the method to the object you're in. example : mycake.cook();
static : when the actions you do inside your method have nothing to do with an object in particular. example : Cake.throwThemAll();
mycake is an instance of a Cake, declared this way : Cake mycake = new Cake();
Cake is the class representing the object.
You should, i guess, have a read at some object oriented programmation course if you still have a doubt about objects, classes and instances.
While Other answers are Correct , that remains the Question that Why you Can't access Instance
method Directly from Class name , In Java all static (methods , fields) bind with Class Name and when Class Is Loading to the Memory (Stack) all static members are Loading to the Stack , and this time Instance Method is not visible to Class. instance Method will Load into Heap portion in the memory and can only be access by Object references .

Categories