Getting access to variable inside function - java

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?

Related

How would I access an int variable from one class to another? (Java)

For example:
In Class One
int killcount = 0;
In Class Two
killcount = 5;
All I want to do I get the variable from one class to another class. How would I do that?
Before trying to work with Bukkit I'd recommend you to get some Java experience first. That's not meant as an insult, but it can get quite confusing if you do it the other way round. Anyways, if you still want to know the answer to your question:
You'll have to create a getter & setter for your "killcount" variable.
class Xyz {
private int killcount;
public void setKillcount(int killcount) {
this.killcount = killcount;
}
public int getKillcount() {
return this.killcount;
}
}
Of course this is a simplified version without checks, but if you want to access the variable from a different class you can create an instance and use the methods to modify it.
public void someMethod() {
Xyz instance = new Xyz();
instance.setKillcount(instance.getKillcount() + 1);
//this would increase the current killcount by one.
}
Keep in mind that you'll have to use the same instance of the class if you want to keep your values, as creating a new one will reset them to default. Therefore, you might want to define it as a private variable too.
Consider the examples
public class Test {
public int x = 0;
}
This variable x can be accessed in another class like
public class Test2 {
public void method() {
int y = new Test().x;
// Test.x (if the variable is declared static)
}
}
Ideally, the instance variables are made private and getter methods are exposed to access them
public class Test {
private int x = "test";
public int getX() {
return x;
}
public void setX(int y) {
x = y;
}
}

Protected variable in main method

I declared my local variable to protected that is the same name with other general variable.
My code:
public class jc8 {
private int x = 8;
public static void main(String[] args) {
protected int x = 5; // compile time ERROR
}
}
why ?
You can not use the protected key word inside a method block. This is to modify the access of members, not of local variables. Think about it. your local variable's scope is only the main method. It is, by definition, private to that method.
Example
protected int x = 10;
public static void main(String[] args)
{
// Valid
}
This will allow subclasses of your class to have access to x.
"public", "protected" or "private" are visibility modifiers that can be applied to class members not to local variables.
But more important than that, what do you try to accomplish with this definition?, what its the meaning in your head of a local variable to be protected?, think about this and try to understand "why" this is not possible in java.
o Protected Accessibilty:
Indicates that a member can be accessed from any class in the same package and from the child classes from other packages. A keyword “protected” is used to represent protected accessibility before the data type of a member declaration.
Example:
protected int y;
protected void method(){}
so you can not use protected inside a block of code .you need to declare it outside of block of code
you declared
public static void main(String[] args) {
protected int x = 5; // compile time ERROR
}
Right way is
protected int x = 5;
public static void main(String[] args) {
// compile time ERROR
}
The local variable not modified.
Why your are trying to do it?
Their scope is between method braces.

Java: Access public member from a non-related class?

The following Java code is a stripped down example of the code I need. My question is, how do I access someInt from inside class Second? Note that Second implements another class, so I can not just pass someInt in.
package test1;
public class First {
public int someInt;
public static void main(String[] args) {
First x = new First();
}
public First(){
someInt = 9;
Second y = new Second();
}
}
class Second implements xyz{
public Second(){}
public void doSomething(){
someInt = 10; // On this line, the question lies.
System.out.println(someInt);
}
}
You can't access First's someInt field in Second because Second isn't an inner class of First. The changes below would fix your problem.
package test1;
public class First {
public int someInt;
public static void main(String[] args) {
First x = new First();
}
public First(){
someInt = 9;
Second y = new Second();
}
class Second {
public Second(){
someInt = 10;
System.out.println(someInt);
}
}
}
If you need to access the field in First (and not create a new one in Second), you need to pass a reference to the instance of First when you create the instance of Second.
Second y = new Second(this);
}
}
class Second {
public Second(First f){
f.someInt = 10;
In the terms of your question, "Access public member from a non-related class", the problem is solved by creating a relation. If that isn't allowed, this answer is wrong.
Accessing a public member follows the same syntax rules as accessing a public method (just without the brackets)
But having a public member in a class is usually not a good idea
The most direct way would be to
1) instantiate First
First f = new First()
2) access it directly because you made the instance variable someInt public
f.someInt = 10
A better way would be to provide accessors for someInt in First, and do it that way.
First f = new First();
f.setSomeInt( 10 );
...
int x = f.getSomeInt();
Within your second class, you must have a first class object. Create that object in your second class, then you will be able to access someInt.
You need to get a reference to an instance of First since someInt is not static.

java linked list problem

I have written some Java code with 3 simple classes where the first, Controller, has the main method and creates the instances of the other classes. Floaters is a classes that creates a linked list of Floater instances, each with a particular length and boolean value to say if they are vertical or not. My problem, as it says in the commented lines of the first class, is that both "humans" and "otters" Floaters instances are getting assigned the same values and thus have the same size....
Any suggestions on how to fix this?
Thanks in advance!
public class Controller{
private static Floaters humans;
private static Floaters otters;
public static void main(String[] args)
{
otters = new Floaters();
humans = new Floaters();
otters.addFloater(2, true);
otters.addFloater(3, true);
//this should read "2" and it does
System.out.println(otters.size());
//this should read "0" but reads "2". Why?
//How can I get it to read "0"?
System.out.println(humans.size());
}
}
import java.util.LinkedList;
public class Floaters {
private static LinkedList<Floater> llf;
Floaters()
{
llf = new LinkedList<Floater>();
}
public void addFloater(int length, boolean is_vertical)
{
Floater floater = new Floater(is_vertical, (byte)length);
llf.add(floater);
}
public int size()
{
return llf.size();
}
}
public class Floater {
int length;
boolean is_vertical;
Floater(boolean is_vertical, int length)
{
this.length = length;
this.is_vertical = is_vertical;
}
}
The llf in your Floaters-class is static. When you make variables static, they're linked to the class rather than the instance, and thus both instances of Floaters use the same list.
To correct this, simply remove the static from your declaration of the variable.
in floaters, llf should NOT be static
Because of static:
private static LinkedList<Floater> llf;
In this case static means a class field, shared among all instances of a class.
For example - mathematic functions in Java are declared as static metohods of the class java.lang.Math, matemathematical constants are static atributes of this class. So if you use sin(x), you are using always the same method.

Java instance variable declare and Initialize in two statements

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.

Categories