Hi I'm having problem with initialization in java, following code give me compile error called : expected instanceInt = 100; but already I have declared it. If these things relate with stack and heap stuff please explain with simple terms and I'm newbie to java and I have no advanced knowledge on those area
public class Init {
int instanceInt;
instanceInt = 100;
public static void main(String[] args) {
int localInt;
u = 9000;
}
}
You can't use statements in the middle of your class. It have to be either in a block or in the same line as your declaration.
The usual ways to do what you want are those :
The initialization during the declaration
public class MyClass{
private int i = 0;
}
Usually it's a good idea if you want to define the default value for your field.
The initialization in the constructor block
public class MyClass{
private int i;
public MyClass(){
this.i = 0;
}
}
This block can be used if you want to have some logic (if/loops) during the initialization of your field. The problem with it is that either your constructors will call one each other, or they'll all have basically the same content.
In your case I think this is the best way to go.
The initialization in a method block
public class MyClass{
private int i;
public void setI(int i){
this.i = i;
}
}
It's not really an initialization but you can set your value whenever you want.
The initialization in an instance initializer block
public class MyClass{
private int i;
{
i = 0;
}
}
This way is used when the constructor isn't enough (see comments on the constructor block) but usually developers tend to avoid this form.
Resources :
JLS - Instance Initializers
On the same topic :
Use of Initializers vs Constructors in Java
How is an instance initializer different from a constructor?
Bonus :
What does this code ?
public class MyClass {
public MyClass() {
System.out.println("1 - Constructor with no parameters");
}
{
System.out.println("2 - Initializer block");
}
public MyClass(int i) {
this();
System.out.println("3 - Constructor with parameters");
}
static {
System.out.println("4 - Static initalizer block");
}
public static void main(String... args) {
System.out.println("5 - Main method");
new MyClass(0);
}
}
The answer
Put it in an initializer block.
public class Init {
int instanceInt;
{
instanceInt = 100;
}
public static void main(String[] args) {
int localInt;
int u = 9000;
}
}
Or simply initialize while declaring it:
public class Init {
int instanceInt = 100;
public static void main(String[] args) {
int localInt;
int u = 9000;
}
}
References:
Java Tutorial - Initializing Fields
Java - Initializer Block
You can not have a separate statement to assign values to class members in the declaration area. You have to do this from a function, typically a class method.
For your case, consider doing the assignment as soon as you declare.
You need to do :
int instanceInt = 100;
If it was static you could initialize in a static block.
According to the Java Language Specification:
A class body may contain declarations
of members of the class, that is,
fields (§8.3), classes (§8.5),
interfaces (§8.5) and methods (§8.4).
A class body may also contain instance
initializers (§8.6), static
initializers (§8.7), and declarations
of constructors (§8.8) for the class.
However, the statement
instanceInt = 100;
is none of those things, therefore it is not allowed as part of a class body. What you need to do is this:
int instanceInt = 100;
This is allowed because it is a field declaration that includes a variable initializer.
Related
Please help me I am facing bit problem in Java code.
I am not able to understand how to fix the error.
Please help.
public class A {
private int a = 100;
public void setA(int value) {
a = value;
}
public int getA() {
return a;
}
}
public class B extends A {
private int a = 222;
public static void main(String[] args) {
System.out.println("in main(): ");
a = 123;
System.out.println("a = "+super.a );
}
}
The error I get is:
int a in class Main must be static
First of all, you should tell us the error :).
It looks like you are trying to access a variable in a non-static context from a static context (main method is static).
You should do something like below:
public class B extends A {
public static void main(String[] args) {
B b = new B();
b.setA(123)
System.out.println("a = " + b.getA());
}
}
It doesn't make sense to declare another 'a' variable in the child class. If you want to access 'a' directly, you can declare the field in class A as protected.
First of all, just to be clear prior to going to the code, your 2 classes, given they are both public, must be in their own separate files.
Now let's go to your code. The error lies first in this statements inside your main method:
a = 123;
You are accessing B's instance variable a from a static context -this is one.
Second:
System.out.println("a = "+super.a );
A's instance variable a is never inherited by B because it has a private access modifier.
If you want to access A's a, you could create an instance of A, and use that to call the getA() method which returns the value of A's a
Cheers,
See the code snippets below:
Code 1
public class A {
static int add(int i, int j) {
return(i + j);
}
}
public class B extends A {
public static void main(String args[]) {
short s = 9;
System.out.println(add(s, 6));
}
}
Code 2
public class A {
int add(int i, int j) {
return(i + j);
}
}
public class B extends A {
public static void main(String args[]) {
A a = new A();
short s = 9;
System.out.println(a.add(s, 6));
}
}
What is the difference between these code snippets? Both output 15 as an answer.
A static method belongs to the class itself and a non-static (aka instance) method belongs to each object that is generated from that class. If your method does something that doesn't depend on the individual characteristics of its class, make it static (it will make the program's footprint smaller). Otherwise, it should be non-static.
Example:
class Foo {
int i;
public Foo(int i) {
this.i = i;
}
public static String method1() {
return "An example string that doesn't depend on i (an instance variable)";
}
public int method2() {
return this.i + 1; // Depends on i
}
}
You can call static methods like this: Foo.method1(). If you try that with method2, it will fail. But this will work: Foo bar = new Foo(1); bar.method2();
Static methods are useful if you have only one instance (situation, circumstance) where you're going to use the method, and you don't need multiple copies (objects). For example, if you're writing a method that logs onto one and only one web site, downloads the weather data, and then returns the values, you could write it as static because you can hard code all the necessary data within the method and you're not going to have multiple instances or copies. You can then access the method statically using one of the following:
MyClass.myMethod();
this.myMethod();
myMethod();
Non-static methods are used if you're going to use your method to create multiple copies. For example, if you want to download the weather data from Boston, Miami, and Los Angeles, and if you can do so from within your method without having to individually customize the code for each separate location, you then access the method non-statically:
MyClass boston = new MyClassConstructor();
boston.myMethod("bostonURL");
MyClass miami = new MyClassConstructor();
miami.myMethod("miamiURL");
MyClass losAngeles = new MyClassConstructor();
losAngeles.myMethod("losAngelesURL");
In the above example, Java creates three separate objects and memory locations from the same method that you can individually access with the "boston", "miami", or "losAngeles" reference. You can't access any of the above statically, because MyClass.myMethod(); is a generic reference to the method, not to the individual objects that the non-static reference created.
If you run into a situation where the way you access each location, or the way the data is returned, is sufficiently different that you can't write a "one size fits all" method without jumping through a lot of hoops, you can better accomplish your goal by writing three separate static methods, one for each location.
Generally
static: no need to create object we can directly call using
ClassName.methodname()
Non Static: we need to create a object like
ClassName obj=new ClassName()
obj.methodname();
A static method belongs to the class
and a non-static method belongs to an
object of a class. That is, a
non-static method can only be called
on an object of a class that it
belongs to. A static method can
however be called both on the class as
well as an object of the class. A
static method can access only static
members. A non-static method can
access both static and non-static
members because at the time when the
static method is called, the class
might not be instantiated (if it is
called on the class itself). In the
other case, a non-static method can
only be called when the class has
already been instantiated. A static
method is shared by all instances of
the class. These are some of the basic
differences. I would also like to
point out an often ignored difference
in this context. Whenever a method is
called in C++/Java/C#, an implicit
argument (the 'this' reference) is
passed along with/without the other
parameters. In case of a static method
call, the 'this' reference is not
passed as static methods belong to a
class and hence do not have the 'this'
reference.
Reference:Static Vs Non-Static methods
Well, more technically speaking, the difference between a static method and a virtual method is the way the are linked.
A traditional "static" method like in most non OO languages gets linked/wired "statically" to its implementation at compile time. That is, if you call method Y() in program A, and link your program A with library X that implements Y(), the address of X.Y() is hardcoded to A, and you can not change that.
In OO languages like JAVA, "virtual" methods are resolved "late", at run-time, and you need to provide an instance of a class. So in, program A, to call virtual method Y(), you need to provide an instance, B.Y() for example. At runtime, every time A calls B.Y() the implementation called will depend on the instance used, so B.Y() , C.Y() etc... could all potential provide different implementations of Y() at runtime.
Why will you ever need that? Because that way you can decouple your code from the dependencies. For example, say program A is doing "draw()". With a static language, thats it, but with OO you will do B.draw() and the actual drawing will depend on the type of object B, which, at runtime, can change to square a circle etc. That way your code can draw multiple things with no need to change, even if new types of B are provided AFTER the code was written. Nifty -
A static method belongs to the class and a non-static method belongs to an object of a class.
I am giving one example how it creates difference between outputs.
public class DifferenceBetweenStaticAndNonStatic {
static int count = 0;
private int count1 = 0;
public DifferenceBetweenStaticAndNonStatic(){
count1 = count1+1;
}
public int getCount1() {
return count1;
}
public void setCount1(int count1) {
this.count1 = count1;
}
public static int countStaticPosition() {
count = count+1;
return count;
/*
* one can not use non static variables in static method.so if we will
* return count1 it will give compilation error. return count1;
*/
}
}
public class StaticNonStaticCheck {
public static void main(String[] args){
for(int i=0;i<4;i++) {
DifferenceBetweenStaticAndNonStatic p =new DifferenceBetweenStaticAndNonStatic();
System.out.println("static count position is " +DifferenceBetweenStaticAndNonStatic.count);
System.out.println("static count position is " +p.getCount1());
System.out.println("static count position is " +DifferenceBetweenStaticAndNonStatic.countStaticPosition());
System.out.println("next case: ");
System.out.println(" ");
}
}
}
Now output will be:::
static count position is 0
static count position is 1
static count position is 1
next case:
static count position is 1
static count position is 1
static count position is 2
next case:
static count position is 2
static count position is 1
static count position is 3
next case:
If your method is related to the object's characteristics, you should define it as non-static method. Otherwise, you can define your method as static, and you can use it independently from object.
Static method example
class StaticDemo
{
public static void copyArg(String str1, String str2)
{
str2 = str1;
System.out.println("First String arg is: "+str1);
System.out.println("Second String arg is: "+str2);
}
public static void main(String agrs[])
{
//StaticDemo.copyArg("XYZ", "ABC");
copyArg("XYZ", "ABC");
}
}
Output:
First String arg is: XYZ
Second String arg is: XYZ
As you can see in the above example that for calling static method, I didn’t even use an object. It can be directly called in a program or by using class name.
Non-static method example
class Test
{
public void display()
{
System.out.println("I'm non-static method");
}
public static void main(String agrs[])
{
Test obj=new Test();
obj.display();
}
}
Output:
I'm non-static method
A non-static method is always be called by using the object of class as shown in the above example.
Key Points:
How to call static methods: direct or using class name:
StaticDemo.copyArg(s1, s2);
or
copyArg(s1, s2);
How to call a non-static method: using object of the class:
Test obj = new Test();
Basic difference is non static members are declared with out using the keyword 'static'
All the static members (both variables and methods) are referred with the help of class name.
Hence the static members of class are also called as class reference members or class members..
In order to access the non static members of a class we should create reference variable .
reference variable store an object..
Simply put, from the point of view of the user, a static method either uses no variables at all or all of the variables it uses are local to the method or they are static fields. Defining a method as static gives a slight performance benefit.
Another scenario for Static method.
Yes, Static method is of the class not of the object. And when you don't want anyone to initialize the object of the class or you don't want more than one object, you need to use Private constructor and so the static method.
Here, we have private constructor and using static method we are creating a object.
Ex::
public class Demo {
private static Demo obj = null;
private Demo() {
}
public static Demo createObj() {
if(obj == null) {
obj = new Demo();
}
return obj;
}
}
Demo obj1 = Demo.createObj();
Here, Only 1 instance will be alive at a time.
- First we must know that the diff bet static and non static methods
is differ from static and non static variables :
- this code explain static method - non static method and what is the diff
public class MyClass {
static {
System.out.println("this is static routine ... ");
}
public static void foo(){
System.out.println("this is static method ");
}
public void blabla(){
System.out.println("this is non static method ");
}
public static void main(String[] args) {
/* ***************************************************************************
* 1- in static method you can implement the method inside its class like : *
* you don't have to make an object of this class to implement this method *
* MyClass.foo(); // this is correct *
* MyClass.blabla(); // this is not correct because any non static *
* method you must make an object from the class to access it like this : *
* MyClass m = new MyClass(); *
* m.blabla(); *
* ***************************************************************************/
// access static method without make an object
MyClass.foo();
MyClass m = new MyClass();
// access non static method via make object
m.blabla();
/*
access static method make a warning but the code run ok
because you don't have to make an object from MyClass
you can easily call it MyClass.foo();
*/
m.foo();
}
}
/* output of the code */
/*
this is static routine ...
this is static method
this is non static method
this is static method
*/
- this code explain static method - non static Variables and what is the diff
public class Myclass2 {
// you can declare static variable here :
// or you can write int callCount = 0;
// make the same thing
//static int callCount = 0; = int callCount = 0;
static int callCount = 0;
public void method() {
/*********************************************************************
Can i declare a static variable inside static member function in Java?
- no you can't
static int callCount = 0; // error
***********************************************************************/
/* static variable */
callCount++;
System.out.println("Calls in method (1) : " + callCount);
}
public void method2() {
int callCount2 = 0 ;
/* non static variable */
callCount2++;
System.out.println("Calls in method (2) : " + callCount2);
}
public static void main(String[] args) {
Myclass2 m = new Myclass2();
/* method (1) calls */
m.method();
m.method();
m.method();
/* method (2) calls */
m.method2();
m.method2();
m.method2();
}
}
// output
// Calls in method (1) : 1
// Calls in method (1) : 2
// Calls in method (1) : 3
// Calls in method (2) : 1
// Calls in method (2) : 1
// Calls in method (2) : 1
Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier.
i.e. class human - number of heads (1) is static, same for all humans, however human - haircolor is variable for each human.
Notice that static vars can also be used to share information across all instances
We can put code in a constructor or a method or an initialization block. What is the use of initialization block? Is it necessary that every java program must have it?
First of all, there are two types of initialization blocks:
instance initialization blocks, and
static initialization blocks.
This code should illustrate the use of them and in which order they are executed:
public class Test {
static int staticVariable;
int nonStaticVariable;
// Static initialization block:
// Runs once (when the class is initialized)
static {
System.out.println("Static initalization.");
staticVariable = 5;
}
// Instance initialization block:
// Runs each time you instantiate an object
{
System.out.println("Instance initialization.");
nonStaticVariable = 7;
}
public Test() {
System.out.println("Constructor.");
}
public static void main(String[] args) {
new Test();
new Test();
}
}
Prints:
Static initalization.
Instance initialization.
Constructor.
Instance initialization.
Constructor.
Instance initialization blocks are useful if you want to have some code run regardless of which constructor is used or if you want to do some instance initialization for anonymous classes.
would like to add to #aioobe's answer
Order of execution:
static initialization blocks of super classes
static initialization blocks of the class
instance initialization blocks of super classes
constructors of super classes
instance initialization blocks of the class
constructor of the class.
A couple of additional points to keep in mind (point 1 is reiteration of #aioobe's answer):
The code in static initialization block will be executed at class load time (and yes, that means only once per class load), before any instances of the class are constructed and before any static methods are called.
The instance initialization block is actually copied by the Java compiler into every constructor the class has. So every time the code in instance initialization block is executed exactly before the code in constructor.
nice answer by aioobe
adding few more points
public class StaticTest extends parent {
static {
System.out.println("inside satic block");
}
StaticTest() {
System.out.println("inside constructor of child");
}
{
System.out.println("inside initialization block");
}
public static void main(String[] args) {
new StaticTest();
new StaticTest();
System.out.println("inside main");
}
}
class parent {
static {
System.out.println("inside parent Static block");
}
{
System.out.println("inside parent initialisation block");
}
parent() {
System.out.println("inside parent constructor");
}
}
this gives
inside parent Static block
inside satic block
inside parent initialisation block
inside parent constructor
inside initialization block
inside constructor of child
inside parent initialisation block
inside parent constructor
inside initialization block
inside constructor of child
inside main
its like stating the obvious but seems a little more clear.
The sample code, which is approved as an answer here is correct, but I disagree with it. It does not shows what is happening and I'm going to show you a good example to understand how actually the JVM works:
package test;
class A {
A() {
print();
}
void print() {
System.out.println("A");
}
}
class B extends A {
static int staticVariable2 = 123456;
static int staticVariable;
static
{
System.out.println(staticVariable2);
System.out.println("Static Initialization block");
staticVariable = Math.round(3.5f);
}
int instanceVariable;
{
System.out.println("Initialization block");
instanceVariable = Math.round(3.5f);
staticVariable = Math.round(3.5f);
}
B() {
System.out.println("Constructor");
}
public static void main(String[] args) {
A a = new B();
a.print();
System.out.println("main");
}
void print() {
System.out.println(instanceVariable);
}
static void somethingElse() {
System.out.println("Static method");
}
}
Before to start commenting on the source code, I'll give you a short explanation of static variables of a class:
First thing is that they are called class variables, they belong to the class not to particular instance of the class. All instances of the class share this static(class) variable. Each and every variable has a default value, depending on primitive or reference type. Another thing is when you reassign the static variable in some of the members of the class (initialization blocks, constructors, methods, properties) and doing so you are changing the value of the static variable not for particular instance, you are changing it for all instances. To conclude static part I will say that the static variables of a class are created not when you instantiate for first time the class, they are created when you define your class, they exist in JVM without the need of any instances. Therefor the correct access of static members from external class (class in which they are not defined) is by using the class name following by dot and then the static member, which you want to access (template: <CLASS_NAME>.<STATIC_VARIABLE_NAME>).
Now let's look at the code above:
The entry point is the main method - there are just three lines of code. I want to refer to the example which is currently approved. According to it the first thing which must be printed after printing "Static Initialization block" is "Initialization block" and here is my disagreement, the non-static initialization block is not called before the constructor, it is called before any initializations of the constructors of the class in which the initialization block is defined. The constructor of the class is the first thing involved when you create an object (instance of the class) and then when you enter the constructor the first part called is either implicit (default) super constructor or explicit super constructor or explicit call to another overloaded constructor (but at some point if there is a chain of overloaded constructors, the last one calls a super constructor, implicitly or explicitly).
There is polymorphic creation of an object, but before to enter the class B and its main method, the JVM initializes all class(static) variables, then goes through the static initialization blocks if any exist and then enters the class B and starts with the execution of the main method. It goes to the constructor of class B then immediately (implicitly) calls constructor of class A, using polymorphism the method(overridden method) called in the body of the constructor of class A is the one which is defined in class B and in this case the variable named instanceVariable is used before reinitialization. After closing the constructor of class B the thread is returned to constructor of class B but it goes first to the non-static initialization block before printing "Constructor". For better understanding debug it with some IDE, I prefer Eclipse.
Initializer block contains the code that is always executed whenever
an instance is created. It is used to declare/initialise the common
part of various constructors of a class.
The order of initialization constructors and initializer block doesn’t matter, initializer block is always executed before constructor.
What if we want to execute some code once for all objects of a class?
We use Static Block in Java.
In addition to what was said in previous answers, blocks can be synchronized .. never felt I need to use it, however,it's there
Initialization blocks are executed whenever the class is initialized and before constructors are invoked. They are typically placed above the constructors within braces. It is not at all necessary to include them in your classes.
They are typically used to initialize reference variables. This page gives a good explanation
The question is not entirely clear, but here's a brief description of ways you can initialise data in an object. Let's suppose you have a class A that holds a list of objects.
1) Put initial values in the field declaration:
class A {
private List<Object> data = new ArrayList<Object>();
}
2) Assign initial values in the constructor:
class A {
private List<Object> data;
public A() {
data = new ArrayList<Object>();
}
}
These both assume that you do not want to pass "data" as a constructor argument.
Things get a little tricky if you mix overloaded constructors with internal data like above. Consider:
class B {
private List<Object> data;
private String name;
private String userFriendlyName;
public B() {
data = new ArrayList<Object>();
name = "Default name";
userFriendlyName = "Default user friendly name";
}
public B(String name) {
data = new ArrayList<Object>();
this.name = name;
userFriendlyName = name;
}
public B(String name, String userFriendlyName) {
data = new ArrayList<Object>();
this.name = name;
this.userFriendlyName = userFriendlyName;
}
}
Notice that there is a lot of repeated code. You can fix this by making constructors call each other, or you can have a private initialisation method that each constructor calls:
class B {
private List<Object> data;
private String name;
private String userFriendlyName;
public B() {
this("Default name", "Default user friendly name");
}
public B(String name) {
this(name, name);
}
public B(String name, String userFriendlyName) {
data = new ArrayList<Object>();
this.name = name;
this.userFriendlyName = userFriendlyName;
}
}
or
class B {
private List<Object> data;
private String name;
private String userFriendlyName;
public B() {
init("Default name", "Default user friendly name");
}
public B(String name) {
init(name, name);
}
public B(String name, String userFriendlyName) {
init(name, userFriendlyName);
}
private void init(String _name, String _userFriendlyName) {
data = new ArrayList<Object>();
this.name = name;
this.userFriendlyName = userFriendlyName;
}
}
The two are (more or less) equivalent.
I hope that gives you some hints on how to initialise data in your objects. I won't talk about static initialisation blocks as that's probably a bit advanced at the moment.
EDIT: I've interpreted your question as "how do I initialise my instance variables", not "how do initialiser blocks work" as initialiser blocks are a relatively advanced concept, and from the tone of the question it seems you're asking about the simpler concept. I could be wrong.
public class StaticInitializationBlock {
static int staticVariable;
int instanceVariable;
// Static Initialization Block
static {
System.out.println("Static block");
staticVariable = 5;
}
// Instance Initialization Block
{
instanceVariable = 7;
System.out.println("Instance Block");
System.out.println(staticVariable);
System.out.println(instanceVariable);
staticVariable = 10;
}
public StaticInitializationBlock() {
System.out.println("Constructor");
}
public static void main(String[] args) {
new StaticInitializationBlock();
new StaticInitializationBlock();
}
}
Output:
Static block
Instance Block
5
7
Constructor
Instance Block
10
7
Constructor
Just to add to the excellent answers from #aioobe and #Biman Tripathy.
A static initializer is the equivalent of a constructor in the static context. which is needed to setup the static environment.
A instance initializer is best for anonymous inner classes.
It is also possible to have multiple initializer blocks in class
When we have multiple initializer blocks they are executed (actually copied to constructors by JVM) in the order they appear
Order of initializer blocks matters, but order of initializer blocks mixed with Constructors doesn't
Abstract classes can also have both static and instance initializer blocks.
Code Demo -
abstract class Aircraft {
protected Integer seatCapacity;
{ // Initial block 1, Before Constructor
System.out.println("Executing: Initial Block 1");
}
Aircraft() {
System.out.println("Executing: Aircraft constructor");
}
{ // Initial block 2, After Constructor
System.out.println("Executing: Initial Block 2");
}
}
class SupersonicAircraft extends Aircraft {
{ // Initial block 3, Internalizing a instance variable
seatCapacity = 300;
System.out.println("Executing: Initial Block 3");
}
{ // Initial block 4
System.out.println("Executing: Initial Block 4");
}
SupersonicAircraft() {
System.out.println("Executing: SupersonicAircraft constructor");
}
}
An instance creation of SupersonicAircraft will produce logs in below order
Executing: Initial Block 1
Executing: Initial Block 2
Executing: Aircraft constructor
Executing: Initial Block 3
Executing: Initial Block 4
Executing: SupersonicAircraft constructor
Seat Capacity - 300
This question already has answers here:
Why isn't calling a static method by way of an instance an error for the Java compiler?
(12 answers)
Closed 9 years ago.
I'm trying to fully understand how does "this" work. In my previous post I understood why we use the "this" keyword.
My understanding of static is that the class has one copy of that member. "this" is used to represent the current object. For all objects, the static member variable is same, then why does "this" works on static member variables?
code:
public class OuterInnerClassExample
{
public static void main(String[] args)
{
OuterClass outClassObj = new OuterClass(10);
outClassObj.setInt(11);
outClassObj.setInt(12);
System.out.println("Total Count: " + outClassObj.getCount() );
}
}
class OuterClass
{
private int test;
private static int count; // total sum of how many new objects are created & the times all of them have been changed
public OuterClass(int test)
{
this.test = test;
// count += 1; // preferred as count is static
this.count += 1; // why does this work
}
public int getInt()
{
return this.test;
}
public int getCount()
{
return this.count;
}
public void setInt(int test)
{
this.test = test;
// count += 1; // preferred as count is static
this.count += 1; // why does this work
}
class SomeClass
{
private OuterClass outClassObj;
public SomeClass(int var)
{
outClassObj = new OuterClass(var);
}
public int getVar()
{
return this.outClassObj.getInt();
}
public int getCount()
{
return this.outClassObj.getCount();
}
public void setVar(int var)
{
// OuterClass.this.test = var; // can do this
outClassObj.setInt(var); // preferred
// OuterClass.count += var; // should do this
OuterClass.this.count += var; // why does this work
}
}
}
Also, in the setVar method, we can use ClassName.this to manipulate the objects value, but I think it is better to use a setter as it is much clearer. Is there any advantage of using "this" here that I am missing out?
Please post code to show examples of what you are trying to explain.
The underlying reason is that you can call a static member/method either on the class name MyClass.someStaticField or on an instance of the class new MyClass().someStaticField.
So as long as this is "available", MyClass.someStaticField is equivalent to this.someStaticField.
In your case, you always call this from instance methods so it does exist and the statement compile.
And finally, inner classes (non-static nested classes) contain a reference to their enclosing class, which allows OuterClass.this.count to compile too.
Whenever you do (some expression).staticMember, the compiler only uses the compile-time type of the expression to determine what static member to access. It doesn't matter what the expression is or what value it evaluates to.
It could be ((MyClass)null).someStaticField and it would not make a difference.
I am positive this has probably been answered many many times but I do not know the words to search for to find the answer. So here is the question
I'm using java and I have
int my_var = 3;
thing.myListener(new Listener() {
public void onStart(int posistion) {
my_var <-- I want to get access to my_var
}
});
How do I get access to my_var inside the onStart function. Also what is this type of problem called? Thanks!
You have to make it final. This is an anonymous inner class.
final int my_var = 3;
I would suggest using global variables. Here is an example:
A simple way to utilize "global" variables in Java is to define a class Global with the desired variables as static members of it:
public class Global {
public static int x = 37;
public static String s = "aaa";
}
Such members can be accessed by saying:
public class test {
public static void main(String args[])
{
Global.x = Global.x + 100;
Global.s = "bbb";
}
}
Is that what you are looking for?