public class Test {
int a=10;
a=20;
}
why I can not assign the value as above;
When you declare an instance variable (class member) like this:
public class Test {
int a=10;
}
it means that any instance of class Test will have its own copy of this variable and it will be instantiated to 10.
Java allows an assignment upon declaration of instance variables, but after the variable was already declared it can be assigned only in:
an initializer block
a constructor
a method
which is why the second line will fail to compile.
The value would need to be static or inside of a method to assign the value in this portion of a class. You won't be able to change the value of a in that way unless you declare a static block of code.
try:
public class Test {
private static int a = 20;
}
or
public class Test {
private int a = 10;
public static void Main(String[] args) {
a = 20;
}
or
public class Test {
static {
int a = 10;
a = 20;
}
Try this. It is called initialization block
public class Test {
int a=10;
{a=20;}
}
EDITED:
You can alter variables values only in methods. Java is objective language not procedural.
Related
If I have declared an int variable called impart and declared it in class A, and then I want to call it in class B and display it there. How would I go about doing that? I have heard you can do it by using the reserved keyword 'import', can somebody show me that way?
If you make the variable Public such as
public int potato = 15; Than that can be called in any class.
Or if you want your code to be better declare a private variable then create a method to return said variable.
public class a
{
b wow = new b();
wow.getPotato();
}
public class b
{
private potato;
public b()
{
//You dont neccessarily need this as there is a default constructor
}
public int getPotato()
return potato;
}
you will need to do something like this:
public class A {
// you still have to set a value for i
private int i;
public int getI() {
return i;
}
public class B {
public static void main(String[] args) {
A a = new A();
// now you can use the value with
a.getI();
}
}
you could also set the variable public and access it directly (or make A static as well as the variable, then you can access it without instantiating A) but this is bad coding practice
You create a Object of that Class and then call the getter method for the variable.
A aclass = new A();
aclass.getImport();
If you make the variable static, you can use int b = A.impart;. Making the variable static allows you to cross it over to another class without having to get a reference to the class.
In Switch's case clause, only constants are allowed. When we try to access final variables from another class in to a non static method,
by extending that another class, compile time error is shown as to make those variables as constant (but I have already declared them as final)
package com.another.pack;
public class AnotherPackClass {
public final int a=10,b=90;
public static void main(String[] args) {
}
public static int add(int x,int y){
return (x+y);
}
}
In my test class I have extended above class and using those a,b variables as below
PS: If I declare a,b variables in AnotherPackClass and switchStmnt() in Test class as static and call it in main(), I am able to execute the code.
But I do not want it to use so, I want to leave both of them as non static and do not call it in main().
The error I am getting is "case expression must be constant expression"
Also PS that, I have declared a,b as final . Still I am getting this error.
Please give some reason for it.
That works for me, I'm using inner class :
public class AnotherPackClass {
public final int a = 10, b = 90;
class A extends AnotherPackClass {
void switchstmt() {
int x = 100;
switch (x) {
case a+b:System.out.println("OK");
}
}
}
public static void main(String[] args) {
new AnotherPackClass().new A().switchstmt();
}
public static int add(int x, int y) {
return (x + y);
}
}
For example I've got simple class
class Simple {
private int i = 6;
private static void method(Simple obj) {
System.out.println("Value i: " + obj.i);
}
public void method() {
method(this);
}
public static void main(String[] args) {
new Simple().method();
}
}
Why I can get access to i in static method?
private members can be accessible with in the class. Your static method belongs to the same class. Hence you can access.
Modifier Class Package Subclass World
---------------------------------------------
private **Y** N N N
Update: To avoid the confusion, move the static method to other class and try once.
Don't get confused with static and private/public/[default]. Those are two separate things. A static function can access private non-static field because it is part of the class. And thats whats private does, only restricting access to the class level, without any distinction being made between static or not.
If it's the staticness that's bothering you, obj is a proper "not static" object, which us why it has an accessible non-static field. The method being static is irrelevant.
you are accessing instance of object not directly class variable. when you use direly "i" without reference to object its not allowed.
Private variable visibility is by default in with in class access .
public class Simple {
private int i = 6;
private static void method(Simple obj) {
System.out.println("Value i: " + i); //compile Error ::Cannot make a static reference to the non-static field i
}
public void method() {
method(this);
}
public static void main(String[] args) {
new Simple().method();
}
}
This Q rather for verification:
A static final field can be initialized when it's declared:
public static final int i=87;
or in the static block:
public static final int i;
//..........
static {
...
i=87;
...
}
Is there anywhere, other than the static block, a static final field
public static final int i;
can be initialized?
Thanks in advance.
Note: saw Initialize a static final field in the constructor. it's not specific that the static block is the only place to initialized it outside the declaration.
//==============
ADD:
extending #noone's fine answer, in response to #Saposhiente's below:
mixing in some non-static context:
public class FinalTest {
private static final int INT = new FinalTest().test();
private int test() {
return 5;
}
}
The Java Language Specification states
It is a compile-time error if a blank final (§4.12.4) class variable
is not definitely assigned (§16.8) by a static initializer (§8.7) of
the class in which it is declared.
So the answer to
Is there anywhere, other than the static block, a static final field
can be initialized?
No, there isn't.
It could be "initialized" in any random static method, but only indirectly by using the static block, or the variable initialization.
public class FinalTest {
private static final int INT = test();
private static int test() {
return 5;
}
}
Or like this:
public class FinalTest {
private static final int INT;
static {
INT = test();
}
private static int test() {
return 5;
}
}
Technically, it is not really an initialization in test(), but it acts like one.
No. A field that is static belongs to the class, and a field that is final must be assigned by the time it becomes visible, so a static final field must be initialized either with the declaration or in a static initializer (which both get compiled to the same thing) so that it has a value when the class is finished loading.
It can only be initialized in a set of static code that is always run exactly once. This is usually in its declaration or in a static block, but you could also do something weird like
static final int i;
static int j = i = 1;
which is technically neither of those. Either way, you can't initialize it in any sort of function or constructor because that function might be run more than once; you have to use a static declaration or block of code to run the function and use the return value to initialize it.
I have the following class:
public abstract class A()
{
public static final SomeString = null;
static()
{
SomeString = "aaa";
}
}
When is this static method invoked and how?
What is the purpose in creating such a static method (without name / return type)?
That is not a method, it's a static initialization block, and your syntax is wrong
public abstract class A()
{
public static String SomeString = null;
static
{
SomeString = "aaa";
}
}
The easiest way of initializing fields (static or instance) in Java at the time of their declaration is simply by providing a compile time constant value of a compatible data type. For example:
public class InitializationWithConstants{
public static int staticIntField = 100;
private boolean instanceBoolField = true;
}
This type of initialization has its limitation due to its simplicity and it can not support initialization based even on some moderately complex logic - like initializing only selected elements of a complex array using some logic in a for loop.
Here comes the need for static initialization blocks and initializer blocks for initializing static and instance fields, respectively.
It's a normal block of code enclosed within a pair of braces and preceded by a 'static' keyword. These blocks can be anywhere in the class definition where we can have a field or a method. The Java runtime guarantees that all the static initialization blocks are called in the order in which they appear in the source code and this happens while loading of the class in the memory.
public class InitializationWithStaticInitBlock{
public static int staticIntField;
private boolean instanceBoolField = true;
static{
//compute the value of an int variable 'x'
staticIntField = x;
}
}
Since static initialization blocks are actually code-blocks so they will allow us to initialize even those static fields which require some logical processing to be done for them to get their initial values.
Your syntax is incorrect; it should be:
public abstract class A()
{
public static final String SomeString;
static
{
SomeString = "aaa";
}
}
The static block allows static variables to be initialised when the class is loaded when that initialisation is more complication than simply = something;.
Reference
Syntax aside, you're looking at a static initializer block. They're mentioned here.
Essentially, a static initializer block is a piece of code that executes when a class is loaded, and can be used to initialize static fields in the class.
Example:
public abstract class A
{
public static final String SomeString;
static
{
System.out.println("static{}");
SomeString = "aaa";
}
public static void main(String[]args)
{
System.out.println("main");
}
}
Output:
static{}
main
yeas it's not a method. it is static block and i'st evaluated once when the owner class is loaded.
u can use it for initialize static variable dynamically ...