Why can't we use 'this' keyword in a static method - java

class Sub {
static int y;
public static void foo() {
this.y = 10;
}
}
I understand that this represents the object invoking the method and that static methods are not bound to any object. But in the above mentioned case, the variable y is also static.
If we can invoke static method on class object, why can't we allow static methods to set the static variables of the class.
What is the purpose of this additional constraint?

Because this refers to the object instance. There is no object instance in a call of a static method. But of course you can access your static field (only the static ones!). Just use
class Sub {
static int y;
public static void foo() {
y = 10;
}
}
If you want to make sure you get the static field y and not some local variable with the same name, use the class name to specify:
class Sub {
static int y;
public static void foo(int y) {
Sub.y = y;
}
}

The main reason why we can not use "this" in static method context:-
this :- "this" means current class OBJECT , so its clear that "this" only come in
the picture once we intended to create an Object of that class.
static method:- there is no need to create an object in order to use static method.
means "instance" or object creation doesn't any sense with "static" as per Java rule.
So There would be contradiction,if we use both together(static and this) .
That is the reason we can not use "this" in static method.

this is referring to this instance of the object Sub. As the method is static, there is not an instance of Sub.

To make your code work write it like this:
class Sub {
static int y;
public static void foo() {
Sub.y = 10;
}
}
You can set static fields in static methods, but you don't have access to this in static method because this represents the current instance of the object, and in a static method you have no instance.

This means "this" object but there isn't one. In your case you can use the class name as #tibtof suggests.

"this" keyword is only applicable where an instance of an object is created. And in static method no instance is created because static method belongs to class area.

There is no problem with static methods setting values for static fields.
The only issue is usage of this keyword. Please note that since static methods are processed at the time of class loading, it's all but certain that no "this" exists at the point of time, which is why its only logical the usage of this keyword isn't allowed in a static context.
On the other hand, static method can be invoked from an object because it is made accessible to the object. The intention behind static data members and behaviours is to make it common to all the instances of that class.

Keyword "this" refers to the object that you are operation with. In your case this inside any non-static methods or constructor (if you have one and and if you use "this" inside that), then "this" refers to that particular instance of the class Sub.So it is applicable only when the object is created. But anything in the static context of a class, you can use without even creating object for that as it is resolved during the class loading. "this" resolved only when object is created ( you can even say dynamically for which object). So "this" make sense in static context. Hope it helps. God bless.

when we declare variable and method is static then this is share by among object where this keyword only pointing to current object. suppose you have created five object of class foo then only one copy of made of (int y) shred by all object.so if you access int y using this keyword then compiler get a ambiguity which object have to point because static int y is shared by all object . you have access static variable using class name.

Related

Instance methods can access instance methods directly. What does this mean?

After going through Java documentation I understand that a field declared with 'static' keyword is class variable (or static field) and similarly when using 'static' during method declaration, is a static method (or class method). Class variable and Class methods are reference by class name itself.
Read this and this topics however could not understand following sentences from Java documentation.
What does it mean when it says.....
Not all combinations of instance and class variables and methods are allowed:
Instance methods can access instance variables and instance methods
directly.
Instance methods can access class variables and class methods
directly.
Class methods can access class variables and class methods directly.
The Java doc clearly explains about Class variables and Class methods but above 3 points are confusing to me.
Example Execution
1.Instance methods can access instance variables and instance methods directly.
Some Info:
Instance method are methods which require an object of its class to be
created before it can be called.To invoke a instance method, we have to
create an Object of the class in within which it defined.
Instance variables are declared in a class, but outside a method, constructor
or any block.
class Example1 {
int a = 100; // instance variable
public void printData() { // this an instance method called using an object of class Example1
getData(); // accessing another instance method directly without any object
}
public void getData() {
System.out.println(a); // accessing instance variable 'a' directly without any object
}
}
public class InstanceDemo {
public static void main(String[] args) {
Example1 obj1 = new Example1();
obj1.printData(); // will print 100
}
}
2.Instance methods can access class variables and class methods directly.
Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block.
class Example2 {
static int a = 20; // 'static' / class variable
public void printData() { // instance method
setData(); // accessing class method directly
System.out.println(a); // accessing class variable directly
}
public static void setData() { // class method 'static'
a = 200; // setting value of class variable 'a'
}
}
public class InstanceDemo {
public static void main(String[] args) {
Example2 obj2 = new Example2();
obj2.printData(); // will print 200
}
}
3.Class methods can access class variables and class methods directly.
Static methods are the methods in Java that can be called without creating an
object of class. They are referenced by the class name itself or reference to
the Object of that class.
Memory Allocation: They are stored in Permanent Generation space of heap as
they are associated to the class in which they reside not to the objects of
that class. But their local variables and the passed argument(s) to them are
stored in the stack. Since they belong to the class so they can be called to
without creating the object of the class.
class Example3 {
static int a = 300;
public static void printData() {
getData(); // accessing class method
}
public static void getData() {
System.out.println(a); // accessing class variable 'a'
}
}
public class InstanceDemo {
public static void main(String[] args) {
//calling class method : class method are called using class name.
Example3.printData(); // will print 300
}
}
I think you just need to practice programming, so you can experience how the language works. Understanding the quirks of static access is one of the hardest things to grasp initially. Static members are generally geared towards providing class utility.
An instance method gets a pointer to the instance it's operating on, on the stack, therefore it can access the members of the instance. A static method isn't associated with any particular instance. There's no 'this' reference, thus it can't access instance members.
Instance methods can access instance variables and instance methods
directly.
This means a method that doesn't have a static modifier i.e. an instance method can access any non-static variable as well as call any non-static method.
Instance methods can access class variables and class methods
directly.
This means a method that doesn't have a static modifier i.e. an instance method can access a static variable or call a method with the static modifier.
Class methods can access class variables and class methods directly.
This means a static method can access any static variable as well as call any other method that has a static modifier.
To put it simply, an instance method i.e. a method without the static modifier can access both a static variable as well as a non-static variable and it can also directly call a static method and a non-static method.
On the other hand, a static method can only access static variables and call static methods. it cannot, however, access an instance variable or instance methods directly without an object.

How static method inheritance and static variable inheritance differs?

I got a doubt while going through override functionality in java.
Consider the below code:
class Vehicle {
static int speed = 50;
public static void display() {
System.out.println(speed);
}
}
class Jeep extends Vehicle {
int speed = 100;
void display() { //GETTING COMPILE TIME ERROR
System.out.println(speed);//will print speed of Bike
}
public static void main(String args[]) {
Jeep b = new Jeep ();
System.out.println(b.speed);
}
}
I read that static methods cannot be overridden.
But in the above code, I declared a static variable 'speed' in parent class Vehicle. And I created an instance variable with same name 'speed' in child class. i didn't get any compile time error as I changed the value of the static variable 'speed' in child class.
I am facing compile time issue while trying to override the display method, while I am not getting any error while re-declaring the variable 'speed' even though both are static in parent class.
What may be the reason that, the subclass's speed variable hides the parent class's static speed variable , but not doing the same with the display method and showing compile time error ?
static functions are not part of a particular instance of an object, and polymorphism doesn't really make much sense unless it's applied to an object.
That's why you cannot override a static function.
In your code the subclass defines a field with the same name(speed) which is declared as a new field and the field in the superclass is hidden or in other words shadowed by subclass field with same name.
A shadowed field indicates that it is not inherited by the subclass instead the subclass has declared a field with same name in its scope.
Hiding of field does not affect its value in the superclass. To access the hidden field simply use super.fieldname (Vehicle.speed in your case since its static).
Fields cannot be overidden but only be hidden in java.
Shadowing of fields is considered as bad practice by many as it makes the code less readable and confusing.
As for why static fields cannot be overridden Bathsheba has provided an excellent answer on your question post or refer
Why doesn't Java allow overriding of static methods?

About public final void

i am a new to java . there is something new pops up called public final void. what does that do ? what is the difference between public static void and public final void? I would be greatly appreciated from guys!
public final void method() {}
This method is final, and so can't be overrided in a subclass.
public static void method() {}
This method is static, and so is class-scoped. You can't use class attribute in this method (unless if they are static), and you call it using MyClass.method() instead of anInstance.method().
Finally, void is the return type of the function (meaning the method returns nothing) and public is an access modifier.
Related questions:
About access modifier,
About final,
About when to use static.
That must be a part of method:
public - meaning it could be accessible by any other object
static - meaning it could be accessed by class name in addition to object as well.
void - meaning that method wont return any value. It will do some operations
within the method.
final - Meaning you cant override the method in your sub class.
The final keyword is used for variables when they are constant, their value can be set only once, furthermore a final method cannot be subclassed.
static members belong to the class instead of a specific instance.
When you declare a method final, subclasses of your class will not be able to override it.
When you declare a method static you can call it without creating an object of class.

What happens when I assign static object to non static object?

I wonder what happens when I assign a static object to non-static object ?
For example:
public class Test{
public void test(){
BoneCp cp=BoneCpLoad.getBoneCpPool();
}
}
public class BoneCpLoad{
private static BoneCpPool pool =new BoneCpPool();
public static BoneCp getBoneCpPool(){
return pool;
}
}
Static objects actually don't exist.
In this case static keyword is referred to getBoneCpPool() method. This is perfectly legal and the static method returns an instance of BonceCp object.
static modifier keyword can be applied to methods, and denotes methods that not belong to a particular instance of a class, but to the class itself.
static modifier keyword can be applied to fields too (actually are static reference to objects). In this case denotes fields that not belong to a particular instance of a class, but are share between all class instances of the same type.
This isn't really assigning a static object to a non-static object.
BoneCp cp = BoneCpLoad.getBoneCpPool();
This line is equivalent to
BoneCp cp = new BoneCpPool();
Which is just a normal instantiation of an object.
This whole question is based on a false premise.
In Java, there is no such thing as a static object. All objects live in the heap and their lifetime is determined by reachability.
There is such a thing as a static variable. However, nothing special happens when you assign a reference to a static variable. The variable now just contains a reference to the object. Similarly, nothing special happens when you assign a reference in a static variable to any other kind of variable.

Problems understanding static modifier

I am having difficulty understanding what a "static" method and "static" variable is and it is causing me problems with my code. Here is the code I am having difficulty with:
public class Document{
public void NewBlank(){
Resources.openRawResource(R.raw.blank);
}
}
Why do I get the error "Cannot make a static reference to the non-static method Resource.openRawResource(int) from the type Resources"? Why can't I reference a non-static method?
openRawResources is not a static method, it needs to be invoked in an object, not a type. In order to get an instance of Resources you could call getResources in an activity. Then the resulting code would be
Resources resources = myactivity.getResources();
resources.openRawResource(R.raw.blank);
A static method/variable is one that belongs to the class type, and not to the instances/objects of such type.
Cannot make a static reference to the non-static method
This means that for invoking that method you are trying to, you need a reference to an instance of that class.
Here's an example illustrating the difference:
public class Foo{
public static int staticVariable = 5;
public static void methodStatic(){}
public void nonStaticMethod(){}
}
here's how you can use them:
Foo.nonStaticMethod(); //can call static method referring to the class itself without having an instance
Foo f = new Foo();
f.nonStaticMethod(); //you need an instance of a Foo class in order to call a non-static method
For what concern static variables, these are variables that doesn't belong to a single instance of a class, but are shared between all different instances of the same class:
Foo a = new Foo();
Foo b = new Foo();
System.out.println(a.staticVariable); //print 5
System.out.println(b.staticVariable); //print 5
a.staticVariable = 10;
System.out.println(b.staticVariable); //print 10
(Please, look at the example above just to understand the concept of what a static variable is. You'll get the warning "access a static field in a non-static way" because that's not a proper way to access those variables)

Categories