Creating auto initialized static objects in Java - java

I'm trying to create a subclass which auto creates itself. I defined Base which holds a list of instances. Then I defined Derived with a static member reg. reg is in place initialized by calling Base.Register(), which adds it to the instances list.
In the main() I'm printing the instances list of Base. But there is no initialization and I get an error - the instances list is null.
In a further attempt, I added a list of Booleans to Base. Whenever I register an instance, I'm changing this list. I also print this list in the program. I expected it to force the execution of the Base.register(), but to no avail.
I did find a solution that worked, but I don't appreciate - I could print the result of the Base.register() as saved in the Derived. That would force the static initialization. However, I intend to use the solution for a bunch of derived classes, and I wouldn't want to have to call each derived class directly.
Is there a way to force the static init?
I guess I could use reflections, I'm trying to avoid that at the moment.
EDIT what I am actually trying to do, is to build a set of derived classes (for unit testing). All classes derive Base. I want to avoid the need to create instances separately for each. I'm trying to get a generic solution, in each derived class code (only). Such a solution would be easy to copy & paste.
public class StaticTest {
private static class Base{
private static ArrayList<Base> _instances = null;
private static ArrayList<Boolean> _regs = null;
public static int _count = 0;
public static void init(){
_regs = new ArrayList<>();
for (int i=0;i<10;i++)
_regs.add(false);
}
protected static boolean register(Base b)
{
if (_instances == null)
_instances = new ArrayList<>();
_regs.set(_count++, true);
return _instances.add(b);
}
public static void printAll(){
for (Boolean b: _regs)
System.out.printf("hello %s%n", b.toString());
for (Base b: _instances)
System.out.printf("hello %s%n", b.toString());
}
}
private static class Derived extends Base{
public static boolean _reg = Base.register(new Derived());
}
public static void main(String[] args) {
//System.out.print(Derived._reg ? "0" : "1");
Base.init();
System.out.printf("Base._count = %d%n",Base._count);
Base.printAll();
}
}

Short answer is that static initialization occurs only when a class is first used. When you invoke Base.init(), Derived hasn't been yet used and so register hasn't been called.
Medium answer is that if you uncomment the line System.out, you get a NullPointerException because the static code in Derived calls to register before init initializes the Arraylist. Moving the init to the first line solves it and it works as you wanted.
Final answer, if you're trying to understand how a Java classes initializes and it's limitations, it's ok, but the mechanism you're trying to write is a very bad design. Please provide the real problem you're trying to solve and someone can point you in the right direction.

Related

Can we access static members and static functions of a class with the help of instance variables of that class in java? [duplicate]

This question already has answers here:
What is a class literal in Java?
(10 answers)
Closed 5 years ago.
To illustrate the contrast. Look at the following java snippet:
public class Janerio {
public static void main(String[] args) {
new Janerio().enemy();
}
public static void enemy() {
System.out.println("Launch an attack");
}
}
The above code works very fine and seems to be yes as answer to this question as the output turns to be as follows.
Launch an attack
But at the very next moment when I run the following snippet
public class Janerio {
public static void main(String[] args) {
System.out.println(new Janerio().class);
}
}
I get the compile time error
/Janerio.java:3: error: <identifier> expected
System.out.println(new Janerio().class);}
^
/Janerio.java:3: error: ';' expected
System.out.println(new Janerio().class);}
^
2 errors
I don't see why such a situation comes up because in the previous snippet I was able to access the static "enemy" function with the help of an instance of the class but here it's proving false. I mean why can't I access the ".class" static method with the help of the instance of the class. Am I wrong to consider ".class" to be a static function or member of the class Janerio and is it wrong to be analogous to the static features of both the snippets?
But as soon as I call the ".class" with the class name things appear to be that ".class" is static in nature but it deviates to the be static on calling ".class" with an instance of the class.
public class Janerio {
public static void main(String[] args) {
System.out.println(Janerio.class);
}
}
Output we get:
class Janerio
.class references the Class object that represents the given class. it is used when there isn't an instance variable of the class. Hence it doesn't apply to your usage
Read more here:
https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.8.2
With .class you do not select a field (besides class is a keyword).
It is a pseudo operation, usable with a class name, yielding a Class instance:
int.class, Integer.class, java.util.List.class
Am I wrong to consider ".class" to be a static function or member of the class Janerio?
Yes, it's not a variable and it's definitely not a method. You have to use the Object#getClass method when you want to get the class of an instance.
Yes, you can access these static members of classes that way, but the better practise is to use name of that class instead of the name of specific referece to object of that class. It makes your code clearer to understand and to read as static members of class do not belong to specific object but to whole class. For example:
class MyClass {
static int count = 0;
}
It is better to access this field that way:
MyClass.field = 128;
instead of changing that value using the name of specific reference, for example:
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
obj1.field = 128;
Because it can be confusing when you realize that this way even obj2.field has assigned new value of 128. It might look a bit tricky, so again, I would suggest the first presented method of calling methods or changing values assigned to fields.

Java: Static initialization

can you explain me which is the difference between:
public class Test {
public static final Person p;
static {
p = new Person();
p.setName("Josh");
}
}
and
public class Test {
public static final Person p = initPerson();
private static Person initPerson() {
Person p = new Person();
p.setName("Josh");
return p;
}
}
I have always used the second one, but is there any difference with an static initializer block?
There are of course technical differences (you could invoke the static method multiple times within your class if you wanted, you could invoke it via reflection, etc) but, assuming you don't do any of that trickery, you're right -- the two approaches are effectively identical.
I also prefer the method-based approach, since it gives a nice name to the block of code. But it's almost entirely a stylistic approach.
As Marko points out, the method-based approach also serves to separate the two concerns of creating the Person, and assigning it to the static variable. With the static block, those two things are combined, which can hurt readability if the block is non-trivial. But with the method approach, the method is responsible solely for creating the object, and the static variable's initializion is responsible solely for taking that method's result and assigning it to the variable.
Taking this a bit further: if I have two static fields, and one depends on the other, then I'll declare two methods, and have the second method take the first variable as an explicit argument. I like to keep my static initialization methods entirely free of state, which makes it much easier to reason about which one should happen when (and what variables it assumes have already been created).
So, something like:
public class Test {
public static final Person p = initPerson();
public static final String pAddress = lookupAddress(p);
/* implementations of initPerson and lookupAddress omitted */
}
It's very clear from looking at that, that (a) you don't need pAddress to initialize p, and (b) you do need p to initialize lookupAddress. In fact, the compiler would give you a compilation error ("illegal forward reference") if you tried them in reverse order and your static fields were non-final:
public static String pAddress = lookupAddress(p); // ERROR
public static Person p = initPerson();
You would lose that clarity and safety with static blocks. This compiles just fine:
static {
pAddress = p.findAddressSomehow();
p = new Person();
}
... but it'll fail at run time, since at p.findAddressSomehow(), p has its default value of null.
A static method (second example) is executed every time you call it. A static init block (first example) is only called once on initializing the class.
http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable.
This does not count for final instances, because a final variable can only be initialized once.
initPerson requires calling at some point, whereas the static block is executed when creating the Test object.
The static before a function specifies that you can use that function by calling it on the Class name handle itself. For example, if you want to create a Person object outside the class you can write
Person p = Test.initPerson();
However, there is no advantageous difference between the two as you can access the object p outside the class in both cases.

Why do methods on arrays have to be static (Java)?

I don't understand why methods on arrays, in Java, have to be static. Static methods can only be used on static variables right? So this would mean arrays are static variables, variables shared by a class? But what class would this be?
Can someone help me understand this?
Edit: to be more specific, I am creating methods to act on arrays but if I just write "public int[] expandArr(int[]a, int v)" and I try to use this method in the main method, I get an error saying I can't make a static reference to a non-static method. When I write "public static int[] expandArr(int[]a, int v)" it works then.
I understand you cannot change the size of an array, the method I wrote makes a new array with increased size and copies the first one into it.
Thank you.
You say you tried to write this:
public int[] expandArr(int[]a, int v)
The thing is, you had to write it in some class, since you can't just have free-floating methods in your program. Therefore, it must operate on a instance of the class. For example:
public class MyProgram {
public int[] expandArr(int[]a, int v) { ... }
public static void main(String[] args) { ... }
}
expandArr requires an instance of MyProgram, since you didn't declare it to be static. And that has nothing to do with arrays. It would be the same if you wrote
public class MyProgram {
public String expandString(String s, int v) { ... }
public static void main(String[] args) {
String s = expandString(args[0], 1); // ILLEGAL
String s2 = args[0].expandString(1); // ILLEGAL
}
}
Although the first parameter of expandString is a String, this actually operates on a MyProgram, and you cannot use expandString without an instance of MyProgram to operate on. Making it static means that you can (the first use of expandString in my example would become legal.)
In general, you can't add methods to a class without modifying the source of that class. If you want to write a new method that does something with objects of a certain class C, and you can't modify class C (perhaps because it's in the Java library or someone else's library), then you'll need to put the method in some other class C2, and most of the time you will need to make the method static since it doesn't involve objects of class C2.
You can't call a non-static method from a static method unless you first instantiate the an object of the class.
e.g.
In class Whatever...
public boolean ok() {
return true;
}
public static void main(String[] args) {
Whatever w = new Whatever();
System.out.println(w.ok());
}
You cant call a non static method from a static context. A static method belongs to the class, non static or instance methods are copied to each instance of the class (they each have their own). If I have 10 instances of class A, and class A has a static method, which all of them share, then I try to invoke a non static method in class A from class A's static method, which instance of class A gets its method invoked? The behavior is undefined.
The question really has nothing to do with arrays.
This question is related: Can't call non static method
I think what you're referring to is the fact that you can't extend an array class and hence can't add a method to it:
// No way to do this
int[] array;
array.myMethod();
This means your only option is to make a static helper method somewhere:
// So you have to do this
int[] array;
Utils.myMethod(array);
class Utils {
static void myMethod(int[] array) {
...
}
}
An example of this is the Arrays class, which has lots of static methods for operating on arrays. Conceptually it would be clearer if these methods could be added to the array classes, but you can't do that in Java (you can in other languages like Javascript).
That is why we use other classes like the ArrayList to make them grow dynamically in size. At the core of an arraylist you will simply find an array that is renewed in size whenever the class figures out it necessary. If I'm understanding your question right.

What is the purpose of static keyword in this simple example? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When should a method be static?
Usually when writing a static method for a class, the method can be accessed using ClassName.methodName. What is the purpose of using 'static' in this simple example and why should/should not use it here? also does private static defeat the purpose of using static?
public class SimpleTest {
public static void main(String[] args) {
System.out.println("Printing...");
// Invoke the test1 method - no ClassName.methodName needed but works fine?
test1(5);
}
public static void test1(int n1) {
System.out.println("Number: " + n1.toString());
}
//versus
public void test2(int n1) {
System.out.println("Number: " + n1.toString());
}
//versus
private static void test3(int n1) {
System.out.println("Number: " + n1.toString());
}
}
I had a look at a few tutorials. E.g. http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
My understanding of it is that instead of creating an instance of a class to use that method, you can just use the class name - saves memory in that certain situations there is no point in constructing an object every time to use a particular method.
The purpose of the static keyword is to be able to use a member without creating an instance of the class.
This is what happens here; all the methods (including the private ones) are invoked without creating an instance of SimpleTest.
In this Example,Static is used to directly to access the methods.A private static method defeats the purpose of "Data hiding".
Your main can directly call test1 method as it is also Static,it dosn't require any object to communicate.Main cannot refer non-static members,or any other non-static member cannot refer static member.
"non-static members cannot be referred from a static context"
You can refer This thread for more info about Static members.
static means that the function doesn't require an instance of the class to be called. Instead of:
SimpleTest st = new SimpleTest();
st.test2(5);
you can call:
SimpleTest.test1(5);
You can read more about static methods in this article.
A question about private static has already been asked here. The important part to take away is this:
A private static method by itself does not violate OOP per se, but when you have a lot of these methods on a class that don't need (and cannot*) access instance fields, you are not programming in an OO way, because "object" implies state + operations on that state defined together. Why are you putting these methods on that class, if they don't need any state? -eljenso
static means that the method is not associated with an instance of the class.
It is orthogonal to public/protected/private, which determine the accessibility of the method.
Calling test1 from main in your example works without using the class name because test1 is a static method in the same class as main. If you wanted to call test2 from main, you would need to instantiate an object of that class first because it is not a static method.
A static method does not need to be qualified with a class name when that method is in the same class.
That a method is private (static or not) simply means it can't be accessed from another class.
An instance method (test2 in your example) can only be called on an instance of a class, i.e:
new SimpleTest().test2(5);
Since main is a static method, if you want to call a method of the class without having to instantiate it, you need to make those methods also static.
In regards to making a private method static, it has more readability character than other. There isn't really that much of a difference behind the hoods.
You put in static methods all the computations which are not related to a specific instance of your class.
About the visibility, public static is used when you want to export the functionality, while private static is intended for instance-independent but internal use.
For instance, suppose that you want to assign an unique identifier to each instance of your class. The counter which gives you the next id isn't related to any specific instance, and you also don't want external code to modify it. So you can do something like:
class Foo {
private static int nextId = 0;
private static int getNext () {
return nextId ++;
}
public final int id;
public Foo () {
id = getNext(); // Equivalent: Foo.getNext()
}
}
If in this case you want also to know, from outside the class, how many instances have been created, you can add the following method:
public static int getInstancesCount () {
return nextId;
}
About the ClassName.methodName syntax: it is useful because it specifies the name of the class which provides the static method. If you need to call the method from inside the class you can neglect the first part, as the name methodName would be the closest in terms of namespace.

How and where to use Static modifier in Java?

How and where should we use a Static modifier for:
1. Field and
2. Method?
For example in java.lang.Math class, the fields methods like abs(), atan(), cos() etc are static, i.e. they can be accessed as: Math.abs()
But why is it a good practice?
Say, I don't keep it static and create an object of the class and access it, which anyways I can, I will just get a warning that, you are trying to access a static method in a non static way (as pointed out by #duffymo, not in case of Math class).
UPDATE 1:
So, utility method, should be static, i.e. whose work is only dependent on the method parameters. So, for example, can the method updateString(String inputQuery, String highlightDoc) should have been a static method in this question?
You can think of a 'static' method or field as if it were declared outside the class definition. In other words
There is only one 'copy' of a static field/method.
Static fields/methods cannot access non-static fields/methods.
There are several instances where you would want to make something static.
The canonical example for a field is to make a static integer field which keeps a count across all instances (objects) of a class. Additionally, singleton objects, for example, also typically employ the static modifier.
Similarly, static methods can be used to perform 'utility' jobs for which all the required dependencies are passed in as parameters to the method - you cannot reference the 'this' keyword inside of a static method.
In C#, you can also have static classes which, as you might guess, contain only static members:
public static class MyContainer
{
private static int _myStatic;
public static void PrintMe(string someString)
{
Console.Out.WriteLine(someString);
_myStatic++;
}
public static int PrintedInstances()
{
return _myStatic;
}
}
Static uses less memory since it exists only once per Classloader.
To have methods static may save some time, beacuse you do not have to create an object first so you can call a function. You can/should use static methods when they stand pretty much on their own (ie. Math.abs(X) - there really is no object the function needs.) Basically its a convenience thing (at least as far as I see it - others might and will disagree :P)
Static fields should really be used with caution. There are quite a few patterns that need static fields... but the basics first:
a static field exists only once. So if you have a simple class (kinda pseudocode):
class Simple {
static int a;
int b;
}
and now you make objects with:
Simple myA = new Simple();
Simple myB = new Simple();
myA.a = 1;
myA.b = 2;
myB.a = 3;
myB.b = 4;
System.out.println(myA.a + myA.b + myB.a + myB.b);
you will get 3234 - because by setting myB.a you actually overwrite myA.a as well because a is static. It exists in one place in memory.
You normally want to avoid this because really weird things might happen. But if you google for example for Factory Pattern you will see that there are actually quite useful uses for this behaviour.
Hope that clears it up a little.
Try taking a look at this post, it also gives some examples of when to and when not to use static and final modifiers.
Most of the posts above are similar, but this post might offer some other insight. When to use Static Modifiers
Usually when the method only depends on the function parameters and not on the internal state of the object it's a static method (with singletone being the only exception). I can't imagine where static fields are really used (they're the same as global variables which should be avoided).
Like in your example the math functions only depend on the parameters.
For a field you should keep it static if you want all instances of a given class to have access to its value. For example if I have
public static int age = 25;
Then any instance of the class can get or set the value of age with all pointing to the same value. If you do make something static you run the risk of having two instances overwriting each others values and possibly causing problems.
The reason to create static methods is mostly for utility function where all the required data for the method is passed in and you do not want to take the over head of creating an instance of the class each time you want to call the method.
You can't instantiate an instance of java.lang.Math; there isn't a public constructor.
Try it:
public class MathTest
{
public static void main(String [] args)
{
Math math = new Math();
System.out.println("math.sqrt(2) = " + math.sqrt(2));
}
}
Here's what you'll get:
C:\Documents and Settings\Michael\My Documents\MathTest.java:5: Math() has private access in java.lang.Math
Math math = new Math();
^
1 error
Tool completed with exit code 1
class StaticModifier
{
{
System.out.println("Within init block");//third
}
public StaticModifier()
{
System.out.println("Within Constructor");//fourth
}
public static void main(String arr[])
{
System.out.println("Within Main:");//second
//StaticModifier obj=new StaticModifier();
}
static
{
System.out.print("Within static block");//first
}
}

Categories

Resources