Local static variables and Java - java

I was wondering how to achieve the local static variable in java. I know Java wount support it. But what is the better way to achieve the same? I donot want the other methods in my class to access the variable, but it should retain the value across the invocations of the method.
Can somebody please let me know.

I don't think there is any way to achieve this. Java does not support 'local static' a la C, and there is no way to retrofit this while still keeping your sourcecode "real Java"1.
I donot want the other methods in my class to access the variable, but it should retain the value across the invocations of the method.
The best thing would be to make it an ordinary (private) static, and then just don't access it from other methods. The last bit should be easy ... 'cos you are writing the class.
1 - I suppose you could hack something together that involves preprocessing your code, but that will make all sorts of other things unpleasant. My advice is don't go there: it is not worth the pain.

Rather than trying to actually protect the variable, making the code more obscure and complicated, consider logical protection by comment and placement. I declare normal fields at the start of the class, but a field that should only be accessed from one method just before that method. Include a comment saying it should only be used in the one method:
// i should be used only in f
private int i;
/**
* Documentation for f().
*/
public void f(){
System.out.println(i++);
}

What you want is the ability to constraint intermediate computation results within the relevant method itself. To achieve this, you can refer to the following code example. Suppose you want to maintain a static variable i across multiple calls of m(). Instead of having such a static variable, which is not feasible for Java, you can encapsulate variable i into a field of a class A visible only to m(), create a method f(), and move all your code for m() into f(). You can copy, compile, and run the following code, and see how it works.
public class S {
public void m() {
class A {
int i;
void f() {
System.out.println(i++);
}
}
A a = new A();
a.f();
a.f();
a.f();
}
public static void main(String[] args) {
S s = new S();
s.m();
}
}

In theory, yes - but not in conventional manners.
What I would do to create this:
Create that Object in a totally different class, under the private modifier, with no ability to be accessed directly.
Use a debugging tool, such as the JDI to find that variable in the other class, get it's ObjectReference and manipulate directly or create a new variable which references to that object, and use that variable, which references to the object, in your method.
This is quite complicated, as using the JDI is tough, and you would need to run your program on 2 processes.
If you want to do this, I suggest looking into the JDI, but my honest answer would be to look for another solution.

Based on dacongy's idea of using a method local class I created a simple solution:
public class Main {
public static String m() {
class Statics {
static String staticString;
}
if (Statics.staticString == null)
Statics.staticString = "My lazy static method local variable";
return Statics.staticString;
}
}

Related

Is it necessary for instance methods to access instance variable in java?

public class Main {
void sum(int a, int b) {
int c = a + b;
System.out.println(c);
}
public static void main(String args[]) {
Main ob = new Main();
ob.sum(10, 125);
}
}
In the above code there is no instance variable, but I have read that if a method is an instance method it should access instance variable. So is 'sum' an instance method?
sum is an instance method here, because it's not static and requires an instance of the object. You create your instance here:
Main ob = new Main();
In this particular case sum could indeed be made static, slightly simplifying the code by not requiring an instance.
I have read that if a method is an instance method it should access instance variable
I suspect what you were reading is suggesting that if a method doesn't interact with the instance at all then it probably should be static. There may be mention of the term "pure function" in the text somewhere.
I wouldn't go so far as to say that all potentially static methods everywhere should be made static as a universal rule. It really comes down to the semantics of the object itself. Since the object you have here has very little semantic context, this one tiny example could easily go either way.
But suppose you expanded your object to also include methods for subtract, multiply, divide, etc. As the object expands, suppose one or more of those additional methods did use instance variables. It would be a jarring experience to have an object with multiple semantically-similar methods, some of which are static and some of which are not.
Rather than focus on any particular rule that someone gives you, focus on what you are intending to build as your object. If you think that it should be static, make it as such. If you feel that it shouldn't, then don't. If you're unsure, then as an exercise implement both and see which you prefer in that particular case.
Looking to the future plans for what you're intending to build is important, because the more code you have relying on your object throughout the application the harder it will be to change from static to instance or vice-versa.
Yes, 'sum' an instance method because any non-static method is an instance method.
Moreover, It is not necessary that an instance method should access instance variable.
The correct statement is "if a method is an instance method it can access instance variable.

Count Instances of Class

I am looking for a way to programatically get the number of instances of a certain class type in .NET and Java.
Say for example I have class Foo. I want to be able to, in the same process, get a current count of all instance of Foo.
However I cannot modify Foo, so a static int with counting is out. Also I cannot just add all instances I make to some static list and count that. I want to be able to just say:
System.GC.numberOf< Foo >()
or something.
I was looking through the garbage collectors but I could not find any relevant methods.
If you can't modify the class directly (perhaps because it is a built-in class?), could you create a wrapper, or a subclass that inherits the original?
public class subFoo extends foo
{
protected static int count = 0;
public subFoo()
{
count++;
super();
}
protected void finalize() throws Throwable
{
count--;
super.finalize();
}
public static int getInstanceCount()
{
return count;
}
}
This example is Java and may have some syntax issues 'cause I'm a little rusty.
Of course, you'd have to be sure to redeclare all your foo as subFoo throughout the rest of your code.
Another somewhat exotic way to do it would be to use aspect-oriented techniques to instrument the constructor(s) of the class(es) in question. Take a look at AspectJ, for example.
Do you have control of how the Java VM is being run? If so, you can write a quick and dirty debugger agent... http://download.oracle.com/javase/1.5.0/docs/guide/jvmti/jvmti.html#writingAgents
See the events "VM Object Allocation" and "Object Free"
As already commented, there are similar questions in SO.
One hack you can use - a big one IMO - is to change the Object class: see this answer
Resume:
copy the source of Object
add counting to its constructor (finalize)
add method to read the count
prepend the directory with the compiled class to the boot classpath (-Xbootclasspath)
Quick and dirty: if you can't change the class, maybe you can just put a counter in another part of the project, incrementing it when you instantiate said class?

Deferred initialization of immutable variables

I've been using scala's lazy val idiom a lot and I would like to achieve something similar in Java. My main problem is that to construct some value I need some other value which is not known at object construction time, but I do not want to be able to change it afterwards. The reason for that is, I'm using a GUI library which instanciates the object on my behalf and calls a different method when everything I need is created, which is when I know the values I need.
Here are the properties I try to achieve:
* Immutability of my variable.
* Initialization in some other method than the constructor.
I do not think this is possible in Java, for only final achieves immutability of the variable and final variables cannot be initialized outside of the constructor.
What would be the closest thing in Java to what I am trying to achieve ?
One way to do it would be to push the actual instantiation of the value in question into another class. This will be final, but won't be actually created until the class is loaded, which is deferred until it is needed. Something like the following:
public class MyClass
{
private static class Loader
{
public static final INSTANCE = new Foo();
}
Foo getInstance()
{
return Loader.INSTANCE;
}
}
This will lazily initialise the Foo as and when desired.
If you absolutely need the Foo to be an instance variable of your top-level class - I can't think of any way off-hand to do this. The variable must be populated in the constructor, as you noted.
In fact I'm not sure exactly how Scala gets around this, but my guess would be that it sets the lazy val variable to some kind of thunk which is replaced by the actual object when first evaluated. Scala can of course do this by subverting the normal access modifiers in this case, but I don't think you can transparently do this in Java. You could declare the field to be e.g. a Future<Foo> which creates the value on first invocation and caches it from that point on, but that's not referentially transparent, and by the definition of final I don't see a way around this.
Andrzej's answer is great, but there is also a way to do it without changing the source code. Use AspectJ to capture Constructor invocations and return non-initialized objects:
pointcut lazyInit() : execution(* com.mycompany.expensiveservices.*.init(*));
void around() : lazyInit() && within(#Slow *) {
new Thread(new Runnable(){
#Override
public void run(){
// initialize Object in separate thread
proceed();
}
}
}
Given this aspect, all constructors of objects marked with a #Slow annotations will be run in a separate thread.
I did not find much reference to link to, but please read AspectJ in Action by Ramnivas Laddad for more info.

Java Variables Basics

Ok, so I am about to embarrass my self here but I am working on a project that I will need to get some help on so I need to get some conventions down so I don't look too stupid. I have only been doing java for 2 months and 100% of that has been on Android.
I need some help understanding setting up variables and why I should do it a certain way.
Here is an example of my variables list for a class:
Button listen,feed;
Context context = this;
int totalSize = 0;
int downloadedSize = 0;
SeekBar seek;
String[] feedContent = new String[1000];
String[] feedItems = new String[1000];
ListView podcast_list = null;
HtmlGrabber html = new HtmlGrabber();
String pkg = "com.TwitForAndroid";
TextView progress = null;
long cp = 0;
long tp = 0;
String source = null;
String pageContent = null;
String pageName = "http://www.shanescode.com";
DataBaseHelper mdbHelper = new DataBaseHelper(this);
int songdur = 0;
So all of these are variables that I want to use in all through the whole class. Why would I make something a static, or a final. I understand Public but why make something private?
Thanks for your help and please don't be too harsh. I just need some clarification.
These words all alter the way the variable to which they are applied can be used in code.
static means that the variable will only be created once for the entire class, rather than one for each different instance of that class.
public class MyClass{
public static int myNumber;
}
In this case the variable is accessed as MyClass.myNumber, rather than through an instance of MyClass. Static variables are used when you want to store data about the class as a whole rather than about an individual instance.
final prevents the variable's value from changing after it is set the first time. It must be given an initial value either as part of its declaration:
public final int myNumber = 3;
or as part of the class's constructor:
public MyClass(int number){
this.myNumber = 3;
Once this is done, the variable's value cannot be changed. Keep in mind, though, that if the variable is storing an object this does not prevent the object's variable from being changed. This keyword is used to keep a piece of data constant, which can make writing code using that data much easier.
private modifies the visibility of the variable. A private variable can be accessed by the instance which contains it, but not outside that:
public class MyClass{
private int myNumber;
public void changeNumber(int number){
this.myNumber = number; //this works
}
}
MyClass myInstance = new MyClass();
myInstance.myNumber = 3; //This does not work
myInstance.changeNumber(3) //This works
Visibility is used to control how a class's variables can be used by other code. This is very important when writing code which will be used by other programmers, in order to control how they can access the internal structure of your classes. Public and private are actually only two of the four possible levels of visibility in Java: the others are protected and "no (visibility) modifier" (a.k.a not public or private or protected). The differences between these four levels is detailed here.
static = same for all instances of a class.
final = unchanging (reference) for a particular instance.
If you needed some field (aka a class variable) to be shared by all instances of a class (e.g., a constant) then you might make it static.
If you know some field is immutable (at least, it's reference is immutable) in an instance, then it is good practice to make it final. Again, constants would be a good example of a field to make final; anything that is constant within an instance from construction time on is also a good candidate for final.
A search for "java final static" gives pretty useful further reference on the use of those keywords.
The use of the private keyword controls what can accessed by other classes. I'd say it's biggest use is to help developers "do the right thing" - instead of accessing the internals of the implementation of another class, which could produce all sorts of unwanted behavior, it forces using accessor/mutator methods, which the class implementor can use to enforce the appropriate constraints.
Private
The idea behind using private is information hiding. Forget about software for a second; imagine a piece of hardware, like an X-Box or something. Somewhere on it, it has a little hatch to access the inside, usually sporting a sticker: "open this up and warranty is void."
Using private is sticking a sticker like that in your software component; some things are 'inside' only, and while it would be easy for anyone to open it up and play with the inside anyways, you're letting them know that if they do, you're not responsible for the unexpected behavior that results.
Static
The static keyword does not mean "same for all instances of a class"; that's a simplification. Rather, it is the antonym of "dynamic". Using the static keyword means "There is no dynamic dispatching on this member." This means that the compiler and not the run-time determines what code executes when you call this method.
Since thee are no instances of objects at compile-time this means that a static member has no access to an instance.
An example:
public class Cat {
public static void speak() { System.out.println("meow"); }
}
public class Lion extends Cat {
public static void speak() { System.out.println("ROAR"); }
}
// ...
public static void main(String argv[]) {
Cat c = new Lion();
c.speak();
}
The above prints "meow" - not "roar" - because speak is a static member, and the declared type of c is Cat, so the compiler builds in such a way that Cat.speak is executed, not Lion.speak. Were there dynamic dispatching on static members, then Lion.speak would execute, as the run-time type of c is Lion.
Another thing that might trip you up is this:
Not everything has to be a class level variable; you should have a variable defined for the smallest scope it needs to be defined.
So as an example, suppose your class only has one method which uses your TextView progress variable. Move that declaration into the method that needs it. This way it tidies things up and helps you make more robust code by separating out things that are really separate.
I don't know why you would make anything private.
Folks will chime in and say that private is a Very Important Thing.
Some folks will claim that you can't do encapsulation without private. Most of this seems to be privacy for privacy's sake.
If you are selling your code to someone else, then you must carefully separate the interface elements of your class from the implementation details of your class. In this case, you want to make the implementation private (or protected) so that -- for legal purposes -- the code you sell doesn't expose too much of the implementation details.
Otherwise, if you're not selling it, don't waste a lot of time on private.
Invest your time in separating Interface from Implementation. Document the Interface portions carefully to be sure you're playing by the rules. Clearly and cleanly keep the implementation details separate. Consider using private as a way to have the compiler "look over your shoulder" to be sure you've really separated interface from implementation.
One of the aspects of the object oriented approach that has made it so wildly popular is that you can hide your variables inside of a class. The class becomes like a container. Now you as the programmer get to decide how you want the users of your class to interact with it. In Java, the tradition is to provide an API -- a public interface for your class using methods of the class.
To make this approach work, you declare your variables as private ( which means only methods within your class can access them ) and then provide other methods to access them. For example,
private int someNumber;
This variable can only be accessed from within your class. Do you think others might need access to it from outside of the class? You would create a method to allow access:
public int getSomeNumber()
{
return someNumber;
}
Perhaps users of your class will also need the ability to set someNumber as well. In that case, you provide a method to do that as well:
public void setSomeNumber( int someNumber )
{
this.someNumber = someNumber;
}
Why all of this work just to get access to a class member that you could just as easily declare as public? If you do it using this approach, you have control over how others access the data in your class. Imagine that you want to make sure that someNumber only gets set to be a number < 100. You can provide that check in your setSomeNumber method. By declaring your variables to have private access, you protect your class from getting used incorrectly, and make it easier on everyone who needs to use it -- including yourself!
Declaring a variable to have static access means that you do not need an instance of the class to access the variable. In Java, generally you write a class and then create an instance of it. You can have as many instances of that class as you want, and they all keep track of their own data. You can also declare variables that are part of the class itself, and this is where the static keyword comes in. If you create a variable...
static int classVariable = 0;
the variable can be accessed without a class instance. For example, you might see this done from time to time:
public static final int MY_CONSTANT = 1;
While there are better ways to do this now, it is still a common pattern. You use this variable without any instance of the class like this:
myInstance.setSomeNumber( MyClass.MY_CONSTANT );
java.awt.Color uses static variables this way. You can also declare methods to be static ( look at public static void main, the starting point for your programs ). Statics are useful, but use them sparingly because creating instances of classes can often result in better designs.
Finally ( pun intended ), why would you ever want to declare a variable to be final? If you know that the value should never change, declaring it as final means that if you write some code that tries to change that value, the compiler will start complaining. This again helps protect from making silly mistakes that can add up to really annoying bugs.
If you look at the static variable example above, the final keyword is also used. This is a time when you have decided that you want to make a variable public, but also want to protect it from being changed. You do this by making it public and final.

Reference Static Methods/Variables in Java from an Instance

Can anyone explain to me why java allows you to access static methods and members from an instance? A bad example, if I have a class called RedShape and it has a static method called getColor() which returns "red", why does java allow you to call the static method from an instance of RedShape? To me this seems to violate some of the core concepts of OO language design. At the least, it should come with a compiler warning.
Thanks in advance.
Edit:
In particular, I'm asking about when you have something like
RedShape test = new RedShape();
test.getColor();
where getColor is a static method of the RedShape class. This doesn't make any sense that it's allowed and doesn't give a compiler warning on the command line via javac. I see that it's "strongly discouraged", but was curious if there was a technical or reasonable reason behind why it's allowed outside of "because C++ allows it."
I don't see anything wrong with calling a static method from an instance. What's wrong with that? In particular, quite often there are methods which are useful within the logic of a class, but which don't actually need to manipulate the instance itself.
I do object to calling a static method via an instance reference. Classic example:
Thread thread = new Thread(...);
thread.sleep(5000); // Doesn't do what it looks like
This comes with a compiler warning in some IDEs - certainly in Eclipse, assuming you turn it on. (Java / Compiler / Errors and Warnings / Code Style / Non-static access to static member.) Personally I consider that a mistake in the design of Java. (It's one of the mistakes that C# managed to avoid copying.)
There's really no reason why you can actually do this.
My only guess was that it would allow you to override static methods, but you can't.
If you try the following scenario:
Banana has a static method called 'test' (this prints 'banana')
Apple extends Banana and "overrides" the static method called 'test' (this prints 'apple')
and you do something like this:
public static void main(String[] args) {
Apple apple = new Apple();
Banana banana = new Banana();
Banana base = new Apple();
apple.test();
banana.test();
base.test();
}
The resulting output is:
apple
banana
banana
So effectively, it's pretty useless.
The access to static methods allows you to share values between instances of the same class or even get the values without needed to create a class instance.
There are cases where it's convenient and is no OO language violation.
I bet it's because the original designers were porting capability from C++, and by the time 20/20 hindsight hit, it was a backwards compatibility issue.
That, or because when you call a method within a class, even though you don't have to prefix everything with this. the compiler inserts it (or equivalent) including for static methods. If static methods couldn't be called from instances, then tacking this. on the front might be a problem (or would force coders to tack class name on the front of static methods whenever they wanted to use them within an actual instance).
Anyway, the answers are speculative unless we get one of the early language developers to answer.
public class MyClass {
public static String myString;
}
public class AnotherClass {
public void doSomething() {
doAnotherThing();
}
public static doAnotherThing() {
MyClass.myString = "something";
}
Here we are accessing static variable from non-static method (indirectly) by calling static method from non static method.

Categories

Resources