Make a group of variables public in java - 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;

Related

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.

Accessing a private variable through static method in java

Let say I have the following java classes:
Class A:
public class A {
private int x;
public A(int x){
this.x = x;
}
public static void main(String[] args) {
A a = new A(1);
B b = new B(1,2);
System.out.println((A)b.x);
}
}
Class B:
public class B extends A {
public int y;
public B(int x, int y){
super(x);
this.y = y;
}
}
Why does the compiler marks the access to x on this line
System.out.println((A)b.x);
as an error, even though I'm trying to access x from the class in which it is defined?
Is it because of:
1. the use of polymorphism?
2. the use of a static method?
3. the use of the main method?
You need to make it ((A)b).x to properly type cast it
Note : You are trying to type cast the property x to type A. That's the error!
int x is private therefore it can't be reached from outside of the scope of the class. You could mark it as protected. This way it will still have limited scope. Classes that extend A will be able to access the variable freely.
This is because the dot operator has precedence over the cast operator. This will work, because it forces the cast operator to be applied before the dot operator:
System.out.println(((A)b).x);
Demo on ideone.
When you write (A)b.x, the compiler try to cast b.x into A, but x is an int
Moreover, you don't need to cast b into A and you can't access b.x because x is a private field.
You may need a getter for this, like b.getX()
You have follwing issues
Compiler will show "Field not visible" Error,Because you trying to access private method of parent class
Syntactically. operator has precedence over cast operator
And another impotent thing is that No need to cast a child object to parent to access parent specific members, Because they are already inherited to the child, Here the member you are accessing is private ,which is not inherited. Even if you cast to parent you cant access private members using child object.
Because you are trying to cast an int into A. You need to wrap the cast around the object and then call .x.
Your call is equivalent to (A)(b.x), when it should be ((A)b).x.
public static void main(String[] args) {
A a = new A(1);
B b = new B(1,2);
System.out.println(((A)b).x);
}
Basically, two issues exist here.
One being that int x is private so it cannot be accessed from the sub-class.
Now even if you change the access criteria of int x to publicor protected; the code will still not work because (A)b.x will try to typecast an integer (read x) to an object (read A). Instead of this, you should use ((A)b).x

Can I use my instance variable as the contructor parameter?

class Myclass{
int x;
Myclass (int i){
x = i;
}
}
That is the code I have in my book. I wanted to know if this code would work?
class Myclass{
int x;
Myclass (x)
}
I also could try
class Myclass{
int x;
Myclass (int x)
}
in response to my first answer...would this work?
The latter code would not work because in Java you have to explicitly state the type. (There are no implicit type declarations)
You may have a parameter or local variable with the same name as an instance variable, yes. In that case, the parameter or local variable will shadow the instance variable. To refer to the instance variable in such a case, use:
this.x
For example, it's common to see this pattern:
class MyClass {
private int x;
public MyClass(int x) {
this.x = x;
}
}
Note that, as Josh M points out, it is not possible to omit the type. If that is what your question was about, then no, you may not.
This will compile:
class Myclass {
int x;
Myclass (int x) {
}
}
However, when you do this you end up with two variables with the same name, the instance variable x, which can be referred to explicitly inside the constructor (or any other class method) as this.x, and the local parameter variable x local to the constructor. If you just refer to x in the constructor you'll get the local one. This is referred to as variable shadowing.
Even though you've decided to give these two variables the same names in your source code, in the code the compiler produces they are completely unrelated. You might as well have named the parameter y.
An experiment to try that might help understanding this is to give the variables different types. Make your instance variable a boolean, for instance. Then you can try different things and see that they really are completely different variables that just happen to have the same name.
After #Chris Hayes' and #Samuel Edwin Ward's answers, here's one trick.
class MyClass {
private int x;
public MyClass(final int x) {
this.x = x;
}
}
The final modifier tells the compiler that that x cannot be modified. If you accidentally write
class MyClass {
private int x;
public MyClass(final int x) {
x = x; // Oopsie!
}
}
the compiler will complain.

Can i declare a static variable inside static member function in Java?

private static int Fibonoci(int n) {
static int first=0;
static int second=1;
static int sum;
if(n>0)
i am getting a error "Illegal Modifier" and if i remove static keyword there is no error and i need those variables to be static
You can not declare varibale as static inside a method.
Inside method all variables are local variables that has no existance outside this method thats why they cann't be static.
static int first=0;
static int second=1;
static int sum;
private static int Fibonoci(int n) {
//do somthing
}
You are trying to write code for fibonacci series and for that you don't need static variables for that just here is some links who describes the sol for that
http://crunchify.com/write-java-program-to-print-fibonacci-series-upto-n-number/
http://electrofriends.com/source-codes/software-programs/java/basic-programs/java-program-find-fibonacci-series-number/
statics at function scope are disallowed in Java.
The Root cause: Static Variables are allocated memory at class loading time because they are part of the class and not its object.
Now, if static variable is inside a method, then that variable comes under the method's scope and JVM will be unable to allocate memory to it.
You can't declare a static variable inside a method, static means that it's a variable/method of a class, it belongs to the whole class but not to one of its certain objects.
This means that static keyword can be used only in a 'class scope' i.e. it doesn't have any sense inside methods.
I don't know what you are trying to achieve, but if you really want these variables to be static then you can declare them as static fields in your class.
Local variables cannot be declared static. In other words Static doesn't apply to local variables.
And I didn't see any use of declaring them static there.
Follow JLs on static fields
A static field, sometimes called a class variable, is incarnated when the class is initialized (ยง12.4).
You have to define static variables as members in class. Variables those are defined within method are local variables and their lifecycles ends at the end of the method. local variables are call specific, member variables are object specific and static variables are class specific variables.
You need to declare the static variables outside of the function:
static int first=0;
static int second=1;
static int sum;
private static int Fibonoci(int n) {
if(n>0)
You can not declare varibale as static inside a method. In otherwords we can say that,
Local variables cannot be declared static.
This varibles called Local Variables, they are inside method scop or constructor, they can't be instance or class variables.
private static int COUNT;// Class Variable
private static int Fibonoci(int n) {
int a =3 ; // local variable
}
I need those variables to be static, okey , Why do you need this? because static variables used for special purpuse, however, you can create static fields like I did above code.

java initializing a field which is a class

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();

Categories

Resources