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.
Related
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.
I know that it's possible to do the following:
public class Indeed{
private class inner {
static final int try1 = 10;
}
}
Why? what's the point of allowing such a declaration?
Moreover it's still possible do the same thing in a local class:
public void doThing() {
class LocalClass {
static final int try1 = 10;
}
}
What's the use of a static final in those bits of code?
I am pretty sure I'll never use them, however I need to understand why they are used as I have an OCPJP7 exam to do.
Thanks in advance.
The purpose of a static variable is to be shared by all instances of the class. In both examples, you can have several instances of your private class / local class, so as specified they will share static variables among instances. What would be pointless is if you could only instantiate your class once.
JLS 8.1.3. : Inner Classes and Enclosing Instances
Inner classes may not declare static members, unless they are constant
variables (§4.12.4), or a compile-time error occurs.
The way I see it in the specs, is not having to answer the following dilemma:
static variables of an inner class are shared amongst all instances of the same outer class instance (but they can have different values from an outer class instance to another)
static variables of an inner class are shared amongst all existing instances in the VM, whatever their outer class instances.
Fortunately, when you declare it final, you know it will be the same for every instance, so you don't have to worry about this problem. That's why it is allowed.
For the question "why do static fields of inner classes have to be final":
This restriction is stated in the JLS as
Inner classes may not declare static members, unless they are constant
variables (§4.12.4), or a compile-time error occurs.
But this doesn't tell us why. Let's think about how we use inner classes. Imagine I write (try to) this.
public class A{
private class B{
static x;
}
public void updateX(int y){
B.x=y;
}
public void printX(){
System.out.println(x);
}
}
What happens when I do this
A one = new A();
A two = new A();
one.doStuff(1);
two.doStuff(2);
one.printX();
two.printX();
What should be printed? 1 then 2 or 2 twice? x is static so it should only exist in one place (in the Klass object of B) but as B is an inner class it should be specific to that instance of A. If we allowed static non final fields we would need to create an instance-specific Klass object per instance of the outer class. Which we don't want to have to do!
Static final fields are therefore allowed as they can live in the Klass object of B happily, and be shared across all instances of the outer class, because they can never change (being final).
public class A
{
public static int i;
}
public class B extends A
{
public static void main(String[] args)
{
System.out.println("print i=" + B.i); // referred to A.i
}
}
My question here is how B.i is referred to the A.i?
If the static variable i is inherited why java allows to define another variable i in B class also?
A public or protected member of A is visible in all subclasses of A.
If the static variable i is inherited why java allows to define another variable i in B class also?
It's hard to speculate as to why. One possible reason is that this allows one to add members to a base class without breaking any derived classes that already happen to have a member with the same name.
Note that, if you define another i in B, it will shadow A.i, making it difficult to access the latter. I've seen people expecting this to behave polymorphically, but it doesn't (your case is slightly different anyway, since A.i is static).
i here is a static variable.A static variable,in layman terms,means a single copy being accessed by all classes.So,since your class B extends A,B has an access to the static variable of A.
If you define the variable locally,then the local value of the variable hides the parent class value.
there are 2 different things, scope and visibility. you can not redefine a variable in same scope twice (though you can redefine them in nested scopes).
But in case of inheritance, the subclass is out of scope of superclass, but yet has the visibility to that variable because of inheritance. So sub class allows you to define variable i again, though it will hide super class's variable. you wont be able to see its value. (unless used any getter from superclass)
Java allows you to change the specific variable value for the extended class.
This is because, static variables are shared between all objects of the same class.
It is a variable which belongs to the class and not to object(instance).
So, when extending the static variables of the parent class are not actually part of the extended class BUT are accessible (as long as they were not private).
Additionally, this can be used to do things such as:
using different STATIC CONSTANT for extended classes.
A use for this is to identify classes based on a STATIC integer as apposed to utilizing instanceof. This can be further combined with a switch to change behavior based on an objects type.
So, in the most basic example imagine we want to create a variable represent TYPE.
class A
{
public static final int NODE_TYPE = NODE_PERSON;
public static final int NODE_PERSON = 0;
public static final int NODE_CAR = 1;
}
class B extends Class A
{
public static int NODE_TYPE = NODE_CAR;
}
This has been used in many frameworks including Eclipse Abstract Syntax Trees:
http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.jdt.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fjdt%2Fcore%2Fdom%2FASTNode.html
You will see a list of STATIC INTEGERS which represent different Node Types.
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.
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)