java initializing a field which is a class - java

sorry, c++ programmer new to java strikes again
i have this code
public class MainView extends View {
static final int DRAW_LIST_SIZE=100;
class EventDrawStuff {
int a;
int b;
int c;
}
static EventDrawStuff m_drawList[] = new EventDrawStuff[DRAW_LIST_SIZE];
class DrumEventDrawStuff {
int x;
int y;
}
static DrumEventDrawStuff m_eventDrawStuff = new DrumEventDrawStuff();
the declaration of m_drawList seems to work ok, the declaration of m_eventDrawStuff doesn't compile. what's the difference, can t just be that m_drawList is an array?
i notice that if i say
static DrumEventDrawStuff[] m_eventDrawStuff = new DrumEventDrawStuff[1];
that is ok but i don't really want it to be an array of one, since its only a single thing.
i realise the way to fix the original code is to initialize m_eventDrawStuff in the constructor but that seem cumbersome and unnecessary.
perhaps i've got the wrong idea altogether, please enlighten me, thanks

You can do it in two way -
Make your inner class static
Create DrumEventDrawStuff object with the help of MainView object.
static DrumEventDrawStuff m_eventDrawStuff = new MainView().new DrumEventDrawStuff();

The problem is that you are trying to instantiate a DrumEventDrawStuff in a static context. DrumEventDrawStuff is an inner class of MainView, which means that each instance of DrumEventDrawStuff has an implicit reference to the instance of MainView that holds it (the "outer this").
If you make DrumEventDrawStuff a static class then you'll be OK because that will remove the implicit outer this:
static class DrumEventDrawStuff {
...
}
At this point you're probably wondering why the non-static EventDrawStuff class can be used in a static context.
The answer is that you are not actually creating any instances of EventDrawStuff when you create the array. Unlike C++, Java does not instantiate any objects when you create a new array. Thus, it's perfectly OK to statically declare and create the array of EventDrawStuff because it will be filled with null values.

Since DrumEventDrawStuff is a non-static inner class here, it needs a "surrounding" instance of MainView. Without that, it cannot be instantiated.
Your array, m_drawList is only the array without instances of EventDrawStuff, otherwise you had the same problem.
If you really want to have those static fields, the classes must be static so they don't need a surrounding instance:
public class MainView extends View {
static final int DRAW_LIST_SIZE=100;
static class EventDrawStuff {
int a;
int b;
int c;
}
static EventDrawStuff m_drawList[] = new EventDrawStuff[DRAW_LIST_SIZE];
static class DrumEventDrawStuff {
int x;
int y;
}
static DrumEventDrawStuff m_eventDrawStuff = new DrumEventDrawStuff();

Related

Why can't we define (assign a value) a variable (field) after it is declared in a class?

In a normal class,
public class MyClass {
int a =12;
}
works fine.
But,
public class MyClass {
int a =12;
int b;
b=13;
}
this gives a compilation error.
I know I am trying to access a field without using an object of that class, so I even tried this->
public class MyClass {
int a =12;
int b;
MyClass m= new MyClass();
m.b=13;
}
but even this doesn't seem to work.
I can accept the fact that this is how things work and move on. But does anyone know the logic behind this?
Thank you in advance.
int a = 12;
This is a variable declaration with initialisation.
b=13;
This is an assignment; a statement; it cannot be part of the declaration. It has to be part of the constructor or method.
It is how Java object definition works.
variable/field declarations
constructors
methods (static or non-static)
You can do it in one of the following two ways:
Use the initialization block as follows:
int b;
{
b = 13;
}
Do the following in the constructor:
b = 13;
Check https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html to learn more about it.

Java-Cannot assign a value to final variable

class SomeClass{
final static int temp;
//temp=30;
SomeClass(int a){
System.out.println("here");
temp=a;
}
}
public class HelloWorld{
public static void main(String args[]){
SomeClass t1 = new SomeClass(10);
SomeClass t2 = new SomeClass(20);
System.out.println("t1:"+t1.temp);
System.out.println("t2:"+t2.temp);
}
}
When I create object t2 of SomeClass I can't assign value 20 to it. What could be the reason here? I cannot understand the final static int type.
You have to understand the two modifiers of the temp variable:
static means makes this a class variable so when you make the assignment in the object constructor, this is not a member of the object, but of the class. On the creation of t2 you make a second assignment to the one and only class variable (not a member variable of the object).
final means that the variable can be assigned a value only once, and therefore the assignment in the construction of t2 fails.
Do you intend for temp to be a member field of the object? Then remove static.
If you intend for temp to be a class variable that is reassigned? Then remove final.
static means belonging at class level. And, final means you only can instantiate it once. So, when you use final static, you are instantiating it once when you create t1. Then, that cannot be reinitialized. See this article.
If you want to have a variable that cannot be changed at object level, remove static.
when you define a variable final static, it means that you define it as a CONSTANT. Only one copy of variable exists which can’t be reinitialize.

Assign a static variable before declaring

I'm learning Java and write the simple code below:
public class Test {
private int a = b;
private final static int b = 10;
public int getA() {
return a;
}
}
public class Hello {
public static void main(String[] args) {
Test test = new Test();
System.out.println(test.getA());
}
}
The result: 10. Well done! It run successfully and have no error.
Can anyone please explain why I can assign a static variable before declaring it?
The assignment
private int a = b;
takes place when you create a new instance of Test (just before the constructor is called).
The declaration and initialization of the static variable b, takes place before the instance is created, when the class is loaded.
The order of the statements doesn't matter, since static variables are always initialized first.
Javavariables are initialised this order:
Static variables of the superclasses if any
static variables of the current class.
Static variables, and static blocks in the order that they are
declared
Instance variables of the superclasses
All instance variables of the current class.
Instance variables, and instance level initialisation blocks, in
declaration order
Therefore "b" is intialized before the "a".
Hope this helps.
Static variables are bound to a class - which of course always exists before instances of the class. Thus, you can freely assign it to instance fields.
The order of declaring variables doesn't really matter in your code as in reality the static variable is going to be initialized before non-static ones.
The code you wrote works well because
private final static int b = 10;
is a class variable (static field). Those type of variables are initialised for first.
Then is executed the line
private int a = b;
which initialise the instance variable (field) a.
In short, it doesn't matter the order in which those variables are declared in your code. Class variables are always declared before instance variables.

Make a group of variables public in java

Is there an easy way to make a group of variables in a class as public. For example to make a group of variables as static, I can use something like below.
class A {
static {
int x;
int y;
}
}
Is there a way to do something similar to make the variables as public. Something like this.
public {
int x;
int y;
}
Edit:
I understood that the static block doesn't do what I supposed it will do. What I need is a java version of something like this in C++
class A {
public:
int x;
int y;
}
Your code sample doesn't make a group of variables static, it declares local variables in a static initialization block.
You'll have to declare each variable as public separately.
The above code declares a static initialization block which is not same as declaring the variables as static. (More info.)
For the problem at hand you have to declare variables public separately.
You could use public int x,y. And be careful about static {} blocks.
static int x,y,z;
This should make a group of variables static... as long as they are of the same type of course. You can also make them all public, private etc.
public static int x,y,z;

Static vs Instance Variables: Difference?

What is the difference between a static and instance variable. The following sentence is what I cant get:
In certain cases, only one copy of a particular variable should be shared by all objects of a class- here a static variable is used.
A static variable represents class wide info.All objects of a class share the same data.
I thought that instance vars were used class wide whereas static variables only had scope within their own methods?
In the context of class attributes, static has a different meaning. If you have a field like:
private static int sharedAttribute;
then, each and every instance of the class will share the same variable, so that if you change it in one instance, the change will reflect in all instances, created either before or after the change.
Thus said, you might understand that this is bad in many cases, because it can easiy turn into an undesired side-effect: changing object a also affects b and you might end up wondering why b changed with no apparent reasons. Anyway, there are cases where this behaviour is absolutely desirable:
class constants: since they are const, having all the classes access the same value will do no harm, because no one can change that. They can save memory too, if you have a lot of instances of that class. Not sure about concurrent access, though.
variables that are intended to be shared, such as reference counters &co.
static vars are instantiated before your program starts, so if you have too many of them, you could slow down startup.
A static method can only access static attributes, but think twice before trying this.
Rule of thumb: don't use static, unless it is necessary and you know what you are doing or you are declaring a class constant.
Say there is a test class:
class Test{
public static int a = 5;
public int b = 10;
}
// here t1 and t2 will have a separate copy of b
// while they will have same copy of a.
Test t1 = new test();
Test t2 = new test();
You can access a static variable with it's class Name like this
Test.a = 1//some value But you can not access instance variable like this
System.out.println(t1.a);
System.out.println(t2.a);
In both cases output will be 1 as a is share by all instances of the test class.
while the instance variable will each have separate copy of b (instance variable)
So
t1.b = 15 // will not be reflected in t2.
System.out.println(t1.b); // this will print 15
System.out.println(t2.b); / this will still print 10;
Hope that explains your query.
Suppose we create a static variable K and in the main function we create three objects:
ob1
ob2
ob3;
All these objects can have the same value for variable K. In contrast if the variable K was an instance variable then it could have different values as:
ob1.k
ob2.k
ob3.k
I think you are thinking about the C/C++ definition of the static keyword. There, the static keyword has many uses. In Java, the static keyword's functionality is described in your post. Anyhow, you can try it for yourself:
public class Test_Static{
static int x;
public static void main(String[] argv){
Test_Static a = new Test_Static();
Test_Static b = new Test_Static();
a.x = 1; // This will give an error, but still compile.
b.x = 2;
System.out.println(a.x); // Should print 2
}
}
and similarly for non static variables:
public class Test_NonStatic{
int x;
public static void main(String [] argv){
Test_NonStatic a = new Test_NonStatic();
Test_NonStatic b = new Test_NonStatic();
a.x = 1;
b.x = 2;
System.out.println(a.x); // Should print 1.
}
}
Consider a class MyClass, having one static and one non-static member:
public class MyClass {
public static int STATICVARIABLE = 0;
public int nonStaticVariable = 0;
}
Now, let's create a main() to create a couple of instances:
public class AnotherClass{
public static void main(String[] args) {
// Create two instances of MyClass
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
obj1.nonStaticVariable = 30; // Setting value for nonstatic varibale
obj1.STATICVARIABLE = 40; //Setting value for static variable
obj2.nonStaticVariable = 50;
obj2.STATICVARIABLE = 60;
// Print the values actually set for static and non-static variables.
System.out.println(obj1.STATICVARIABLE);
System.out.println(obj1.nonStaticVariable);
System.out.println(obj2.STATICVARIABLE);
System.out.println(obj2.nonStaticVariable);
}
}
Result:
60
30
60
50
Now you can see value of the static variable printed 60 both the times, as both obj1 and obj2 were referring to the same variable. With the non-static variable, the outputs differ, as each object when created keeps its own copy of non-static variable; changes made to them do not impact on the other copy of the variable created by another object.
Instance Variables
Any variable that is defined in class body and outside bodies of
methods; and it should not be declared static, abstract, stricftp,
synchronized, and native modifier.
An instance variable cannot live without its object, and it is a part of
the object.
Every object has their own copies of instance variables.
Static Variables (class variables)
Use static modifier
Belong to the class (not to an object of the class)
One copy of a static variable
Initialize only once at the start of the execution.
Enjoy the program’s lifetime

Categories

Resources