I have declared a static variable and am changing its value through a non-static method by invoking it in the Initializer block which will be invoked every time an object is instantiated. Why does this not give me run time or compile time error?
public class FinalKeyWord {
final int age;
static int name;
{
ran();
displayName();
}
public FinalKeyWord() {
this.age = 10;
}
public FinalKeyWord(int a){
this.age = a;
}
void ran(){
Random r = new Random();
int rand = r.nextInt(6);
System.out.println(rand);
name = rand;
}
public void displayAge() {
System.out.println("This is final " + age);
}
public void displayName() {
System.out.println("This is static " + name);
}
public static void main(String[] args) {
FinalKeyWord a = new FinalKeyWord();
//a.displayAge();
//a.displayName();
FinalKeyWord a2 = new FinalKeyWord(35);
//a2.displayName();
}
}
Output:
This is static 2 \n
This is is static 3
a variable being static doesn't mean that you can't change its value later, it means that its allocated once in memory for all instances of the class its in, so whenever you create an new object it will point to the same block in memory for this variable unlike normal variables or instance variables where a new block in memory will be reserved for this variable whenever a new object of this class is created.
From Java Documentation/Tutorials,
Instance methods can access class variables and class methods directly.
So this is perfectly legal,
public class FinalKeyWord {
static int a = 5;
void change() {
a= 10;
}
public static void main(String[] args) {
FinalKeyWord obj = new FinalKeyWord();
System.out.println(a);
obj.change();
System.out.println(a);
}
}
And will print,
5
10
Related
So, I want to execute the sum() of the following block of code:
import java.lang.reflect.Method;
public class LocalOuterClass { // start of outer
private int x = 10;
private Object run() { //start of inner
class LocalInnerClass {
private int y = 20;
public void sum() {
System.out.println(x+y);
}
} //end of inner
LocalInnerClass lc = new LocalInnerClass();
//lc.sum();
return lc;
}
public static void main(String[] args) {
LocalOuterClass Loc = new LocalOuterClass();
Object obj = Loc.run();
System.out.println(obj.getClass());
Method[] methods = obj.getClass().getMethods();
for (Method method : methods) {
String MethodName = method.getName();
System.out.println("Name of the method: "+ MethodName);
}
}
} //end of outer
When I do lc.sum(), the sum() is correctly executed. But when I'm returning an object of the inner class to the main() and try to execute sum(), it gives a compiler error. Doing getClass().getMethods() on the object does print sum() as one of the methods. What should I do to execute the sum() inside main()?
You have to change return type to LocalInnerClass and move LocalInnerClass out of the method:
public class LocalOuterClass {
private int x = 10;
private class LocalInnerClass {
private int y = 20;
public void sum() {
System.out.println(x + y);
}
}
private LocalInnerClass run() {
LocalInnerClass lc = new LocalInnerClass();
//lc.sum();
return lc;
}
public static void main(String[] args) {
LocalOuterClass Loc = new LocalOuterClass();
LocalInnerClass obj = Loc.run();
obj.sum(); // it works!
// ...
}
}
The problem is, that the whole LocalInnerClass is not known to your main-method. It does not help, that it has a public method, if the whole type is unknown. You need to refactor your code in order to change that.
Actually your method run currently returns a value of type Object and you'd need to return a value of type LocalInnerClass, however this is not possible due to type visibility.
There are basically two options you have. One is to move the whole LocalInnerClass to a location that is visible to main (like oleg.cherednik suggested):
class LocalOuterClass {
private int x = 10;
private LocalInnerClass run() { // now we can retun `LocalInnerClass`
return new LocalInnerClass();
}
public static void main(String[] args) {
new LocalOuterClass().run().sum(); // works!
}
private class LocalInnerClass {
private int y = 20;
public void sum() {
System.out.println(x+y);
}
}
}
Another option is to implement/extend a different type that has sum, e.g. like this:
class LocalOuterClass {
private int x = 10;
private Summable run() { //start of inner
class LocalInnerClass implements Summable {
private int y = 20;
public void sum() {
System.out.println(x+y);
}
}
return new LocalInnerClass();
}
public static void main(String[] args) {
new LocalOuterClass().run().sum(); // works as well
}
private interface Summable {
void sum();
}
}
With this interface-option the type LocalInnerClass is still not visible to anyone outside your run-method, however the Summable-interface is and since your LocalInnerClass implements Summable you can return a value of that type.
This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 5 years ago.
class ClassB {
int c=0;
public static void main(String [] args) {
ClassA cla = new ClassA();
c=cla.getValue();
}
}
class ClassA {
int value = 0;
public int getValue() {
ClassA obj=new ClassA();
return obj.value;
}
}
I want to 'int value' of ClassA in 'int c' of class B. The above code shows the error "non static variable c cannot be referred from a static context". Please provide the correct coding for me as I am stuck.
Of course, becuase you can't call a non-static method without instantiating the object that contains this method fisrt, either make all the methods and fields static, or instantiate the class:
class ClassB {
static int c=0;
public static void main(String [] args) {
ClassB clb = new ClassB();
c= clb.getvalueA();
}
public int getvalueA(){
ClassA cla = new ClassA();
return cla.getValue();
}
}
class ClassA {
int value = 0;
public int getValue() {
return value;
}
}
Variable c in class B is not static and main block is static block that's why it showing error.You can not reference non static field from static context.
public class Main {
public static void main(String[] args) {
int retVal;
TestClass a = new TestClass(20);
retVal = a.value;
System.out.println("Value of a: "+retVal);
}
}
class TestClass {
int value;
public TestClass(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
}
Here I am using static keyword to instantiate a variable And I am calling the variable using two different Objects.I want to print the result as 1 and 2 without using the static keyword.Thanks in advance.
public class Test {
static int a = 1;
public void meth() {
System.out.println(a);
a = a + 1;
}
public static void main(String[] args) {
Test a = new Test();
Test b = new Test();
a.meth(); //prints 1
b.meth(); //prints 2
}
}
If you remove the static keyword, you need to share an int variable in your two instances of Test.
For example, using AtomicInteger as a mutable wrapper for int and providing the object when constructing Test:
public class Test {
private final AtomicInteger a;
// + constructor setting a + getter
public void increment() {
a.incrementAndGet();
}
}
public class Main {
public static void main(String[] args) {
AtomicInteger i = new AtomicInteger()
Test a = new Test(i);
Test b = new Test(i);
System.out.println(i.get()); // prints 0
a.increment();
System.out.println(i.get()); // prints 1
b.increment();
System.out.println(i.get()); // prints 2
}
}
Please see below, where I have created an object for the class, and used the method nonstaticMethod to change the value of a non-static integer variable. I'm able to do this without the use of 'this' keyword?
Is nonstaticVariable inside nonstaticMethod same as this.nonstaticVariable ?
package lastcommon;
public class Check {
int nonstaticVariable = 100;
public static void main(String[] args) {
Check obCheck = new Check();
obCheck.nonstaticMethod();
}
void nonstaticMethod()
{
nonstaticVariable = 200;
System.out.println(nonstaticVariable);
}
}
Yes. nonstaticVariable = 200; is short for this.nonstaticVariable = 200; you can see this by printing it after the method call like,
public static void main(String[] args) {
Check obCheck = new Check();
obCheck.nonstaticMethod();
System.out.println(obCheck.nonstaticVariable);
}
How can I get the value of userId passed to this method in my anonymous inner subclass here?
public void doStuff(String userID) {
doOtherStuff(userID, new SuccessDelegate() {
#Override
public void onSuccess() {
Log.e(TAG, "Called delegate!!!! "+ userID);
}
});
}
I get this error:
Cannot refer to a non-final variable userID inside an inner class defined in a different method
I'm pretty sure I can't assign it as final since it's a variable with an unknown value. I had heard that this syntax does preserve scope in some way, so I think there must be a syntax trick I don't quite know yet.
As everyone else here has said, local variables have to be final to be accessed by an inner class.
Here is (basically) why that is... if you write the following code (long answer, but, at the bottom, you can get the short version :-):
class Main
{
private static interface Foo
{
void bar();
}
public static void main(String[] args)
{
final int x;
Foo foo;
x = 42;
foo = new Foo()
{
public void bar()
{
System.out.println(x);
}
};
foo.bar();
}
}
the compiler translates it roughly like this:
class Main
{
private static interface Foo
{
void bar();
}
public static void main(String[] args)
{
final int x;
Foo foo;
x = 42;
class $1
implements Foo
{
public void bar()
{
System.out.println(x);
}
}
foo = new $1();
foo.bar();
}
}
and then this:
class Main
{
private static interface Foo
{
void bar();
}
public static void main(String[] args)
{
final int x;
Foo foo;
x = 42;
foo = new $1(x);
foo.bar();
}
private static class $1
implements Foo
{
private final int x;
$1(int val)
{
x = val;
}
public void bar()
{
System.out.println(x);
}
}
}
and finally to this:
class Main
{
public static void main(String[] args)
{
final int x;
Main$Foo foo;
x = 42;
foo = new Main$1(x);
foo.bar();
}
}
interface Main$Foo
{
void bar();
}
class Main$1
implements Main$Foo
{
private final int x;
Main$1(int val)
{
x = val;
}
public void bar()
{
System.out.println(x);
}
}
The important one is where it adds the constructor to $1. Imagine if you could do this:
class Main
{
private static interface Foo
{
void bar();
}
public static void main(String[] args)
{
int x;
Foo foo;
x = 42;
foo = new Foo()
{
public void bar()
{
System.out.println(x);
}
};
x = 1;
foo.bar();
}
}
You would expect that foo.bar() would print out 1 but it would actually print out 42. By requiring local variables to be final this confusing situation cannot arise.
Sure you can assign it as final - just put that keyword in the declaration of the parameter:
public void doStuff(final String userID) {
...
I'm not sure what you meant about it being a variable with an unknown value; all that final means is that once a value is assigned to the variable, it cannot be re-assigned. Since you're not changing the value of the userID within your method, there's no problem making it final in this case.
In Java 8, this has changed a little bit. You can now access variables that are effectively final. Relevant snippet and example from the Oracle documentation (emphasis mine):
However, starting in Java SE 8, a local class can access local
variables and parameters of the enclosing block that are final or
effectively final.
Effectively final: A non-final variable or parameter whose value is never changed after it is initialized is effectively final.
For example, suppose that the variable numberLength is not declared final, and you
add the highlighted assignment statement in the PhoneNumber
constructor:
PhoneNumber(String phoneNumber) {
numberLength = 7; // From Kobit: this would be the highlighted line
String currentNumber = phoneNumber.replaceAll(
regularExpression, "");
if (currentNumber.length() == numberLength)
formattedPhoneNumber = currentNumber;
else
formattedPhoneNumber = null;
}
Because of this assignment statement, the variable numberLength is not
effectively final anymore. As a result, the Java compiler generates an
error message similar to "local variables referenced from an inner
class must be final or effectively final" where the inner class
PhoneNumber tries to access the numberLength variable:
if (currentNumber.length() == numberLength)
Starting in Java SE 8, if you declare the local class in a method, it
can access the method's parameters. For example, you can define the
following method in the PhoneNumber local class:
public void printOriginalNumbers() {
System.out.println("Original numbers are " + phoneNumber1 +
" and " + phoneNumber2);
}
The method printOriginalNumbers accesses the parameters
phoneNumber1 and phoneNumber2 of the method validatePhoneNumber
What's the problem with making it final as in
public void doStuff (final String userID)
declare the method
public void doStuff(final String userID)
The value needs to be final so that the compiler can be sure it doesn't change. This means the compiler can bind the value to the inner class at any time, without worrying about updates.
The value isn't changing in your code so this is a safe change.