Class initialisation
I've simply want to know why class initialisation is done after the constructor of a superclass has been called.
When the constructor of the superclass uses an abstract function that relies on class attributes it can't work because they aren't initialised until the constructor of the superclass has been finished.The code which was extracted from a concrete problem looks like this:
public class ClassInitialisation {
private static int staticcounter = 0;
public ClassInitialisation() {
new ClassInit();
public static void main( String[] args ) {
new ClassInitialisation();
public class ClassInit extends BaseClass {
private Integer myobject = new Integer(-1);
public ClassInit() {
super();
Integer result = (Integer) getAbstractFeature();
System.out.println( "Value should be 0: " + result.intValue() );
public Integer getAbstractFeature() {
if( myobject.intValue() != -1 ) return( myobject );
myobject = new Integer( staticcounter++ );
System.out.println( "Object created: " + myobject.intValue() );
return( myobject );
} /* ENDCLASS */
public abstract class BaseClass {
private Integer myabstract ;
public BaseClass() {
myabstract = getAbstractFeature();
public abstract Integer getAbstractFeature();
} /* ENDCLASS */
} /* ENDCLASS */
My original code has done a check against null, so finding the bug was hard since the corresponding object was simply created again but the superclass referred to the previous one.
Ciao
Kasimir aka Daniel Kasmeroglu
That is extremely annoying, isn't it? I expect the designers of the Java language would have a good explanation, but I don't know what it is. I have been hit with this problem twice already in the project I am working on. I have seen this question discussed in these forums before, and "why" is interesting but pointless, because the Java gurus are not going to change it. The only solution is to modify your design so that your BaseClass does not call methods that could be overridden in its constructor. And this is probably not going to be easy; it was not easy for me. Extremely annoying.
Similar Messages
-
Hi,
I have the following problem. What do you suggest?
I have an interface A, abstract class B, B's subclasses C and D, and mainClass
interface A
abstract class B implements A {
B b;
public B(String desc)
if (desc.equals("C")) b=new C();
else if (desc.equals("D")) b=new D();
class C extends {
public C() {}
class D extends {
public D() {}
class mainClass{
B b=new B("C"); // but B can not be initiated
}B is an abstract class and can not be initiated, I can not define B as normal class, because in B, I define some abstract methods
and want all its subclasses to define them.
What do you suggest me for enhancement?Hi duffymo,
Your answer quite intersting, can you provide some concrete example!
Do you mean like this:
interface A
class B implements A{
B b;
public B(String desc) {
b=Class.newInstance(desc);
class C extends B
class main {
B=new B(desc);
It seems quite okey, but the problem is that I want subclasses (C and D) to impelement some certain methods. Thus I though B as abstract class
It's called a Factory class or virtual constructor -
that's how you create different runtime types. It's a
GOF Pattern - read about it.
I wouldn't build all that stuff into the abstract B
constructor. That'll force you to modify the B class
every time you add a new subtype - that's not a good
idea. Move that code out into a separate class named
AFactory and give it a static method that does that
creation stuff for you. I know - "That just moves the
changes out of B and into the AFactory" - yes, but I
think that's where they belong.
The java.lang.Class class has a factory method built
into it already - newInstance(). You can use that to
instantiate different subclasses:
A newInstance = Class.newInstance("C");
A anotherInstance = Class.newInstance("D");That's the way I'd do it. - MOD -
Document Class initialising Application
Hi
I have started learning AS3. One thing I seem to be missing
the point over is the following:
I have a Document Class as follows:
package {
import flash.display.*;
import com.Application;
public class EntryPoint extends Sprite {
public function EntryPoint() {
var app:Application = new Application();
The document class creates an instance of the Application
class
package com {
import flash.display.*;
public class Application extends Sprite{
public function Application() {
var mc_root:Sprite = new Sprite();
addChild(mc_root);
var circleTest:CircleTest = new CircleTest();
mc_root.addChild(circleTest);
CircleTest is a library item that has a class reference of
'CircleTest' and a Base Class of 'flash.display.Sprite'.
I can only get the above working if the code is in the
Document Class.
Help would be greatly appreciated
ThanksHi. Without looking closely, I'd think the problem is that
you're adding the circle to the app, but not onto the document
class instance (and neither is app added as a child to your main
class)
so the circle is just in limbo.
You can look at the diagram in Flash Help- under: Basics of
display programming -
Checked Exception and Anonymous classes
Hi I am refering to java certification book that says : If a checked exception is thrown during the execution of initializer expression, then it has to be caught and handled. This restriction does not apply to instance initializer expressions in anonymous classes.
I have codes for the above statement but failed to get the correct result. Is there some problem with the code :
class RoomOccupancyTooHighException extends RuntimeException {} // (1) Unchecked Exception
class TooManyHotelsException extends Exception {} // (2) Checked Exception
class base
public void fun()
System.out.println("base");
class derived
public static base funtion()
return new base()
int a = fu();
int fu()
if(a==1)
throw new TooManyHotelsException();
return 100;
public void fun()
System.out.println("derived");
public static void main(String str[])
base b = funtion();
b.fun();
}In anonynous class initialisation you don't need to declare the exception but you still need to handle it in the calling code.
The code you provided does not compile for that reason. -
Below we have a class containing a static class variable and a static accessor method.
The method is responsible for assigning the variable, which it does on demand.
public class MyClass
private static int INFO = -1;
public static int getInfo()
if(INFO < 0)
try
INFO = ...;
catch(Exception e)
return INFO;
}When using this class is it not safe to assume that the assignment of the variable will ever only occur once for the life of the system that uses this class? (afterall is it static within the class)
I am experiencing the situation whereby EVERY time the method is called, the assignment of the variable is necessary. I can only assume that the static instance of this class in memory has been lost between each call and therefore the state/value of the variable has also been lost.
It is worth noting that no object instances of this class are ever created. The class is accessed only through its static interface. It seems that since no local reference to objects of this class are held in memory then the entire class, along with its internal static state, is cleared from memory (garbage collected?).
How is it possible to ensure that the state of static fields within such a class is preserved over time, without create instances of the class.
JohnWhen using this class is it not safe to assume that
the assignment of the variable will ever only occur
once for the life of the system that uses this class?First of all, you haven't said what you assign it to, so we can't say. If you assign a value less than zero then it will be reassigned next time the method is called.
Secondly, it depends on whether or not you're expecting it to be thread-safe? It isn't.
If your code is not multi-threaded, then the section of code in your getInfo method that assigns the field should only execute once during a single run of an application.
Thirdly, you explicitly assign it (to minus one) at class initialisation time, so stricty speaking, the variale will always be assigned at least once, and will be assigned at least once more if the getInfo method is ever called.
I am experiencing the situation whereby EVERY time the
method is called, the assignment of the variable is
necessary. Can you offer any evidence to this? A small, complete, compilable and executable example that demonstrates the problem will help, and will probably get you an answer pretty quickly around here.
I can only assume that the static instance
of this class in memory has been lost between each
call and therefore the state/value of the variable has
also been lost.Then either there is a bug in your JVM, or at least two versions of the class have been loaded, and at least one of those was not loaded by the system classloader. Without further info, we aren't going to be able to help much more here.
The class is accessed only
through its static interface. It seems that since no
local reference to objects of this class are held in
memory then the entire class, along with its internal
static state, is cleared from memory (garbage
collected?).This is not allowed under the JLS if the class was loaded by the system classloader. If it was loaded by another classloader, then it is only allowed if it can be determined that the class will never again be used throughout the entire run of the application. Since you are referencing the class again, this should not be happening.
How is it possible to ensure that the state of static
fields within such a class is preserved over time,
without create instances of the class.From what you have told us so far, it should be. You will probably have to provide some code for us to help you further. -
Loading icons during applet class init
I load a bunch of icons thusly:
ImageIcon[] typeIcons = {
null,
createImageIcon("context_icon", "Context"),
createImageIcon("featureset_icon", "featureset"),
createImageIcon("format_icon", "format"),
createImageIcon("raster_icon", "grid"),
createImageIcon("projection_icon", "projection")
static ImageIcon createImageIcon(String name, String alt) {
URL url = FeatureEditor.class.getResource(name + ".png");
if(url == null)
throw new IllegalArgumentException("No such image as " + name);
return new ImageIcon(url, alt);
}And display them as table cells.
That works ok, but why does it go screwy on me if I make the typeIcons array static? (The TableCellRenderer complains that the objects are of the wrong type).
I can't see why icon loading can't be initiated during class initialisation rather than in object initialisation.Where the method is defined in the source code won't help- it will get called during the initialisation of the array just as before. Is there really no other class object available that you can use instead for the base of your resources? If there's nothing else in your package, then use Object.class and give the full path, rather than a relative one (assuming you're using the default class loader).
Pete -
In the assertion guide,
http://java.sun.com/j2se/1.4.1/docs/guide/lang/assert.html#design-faq-enable-disable
the following question (8) is presented.
"Why does an assert statement that executes before its class is initialized behave as if assertions were enabled in the class?"
The answer begins
"Few programmers are aware of the fact that a class's constructors and methods can run prior to its initialization."
Would you please explain this sentence (independent of the question)?Yet the exerpt states the reverse - That the
constructors and methods can be called before the
class is initialised.
This shows a static method running a static method,
but construction still occurs after the static
initialisers have. Do they perhaps mean that instance
initialisers may not have been run before the
constructor completes? This is certainly possible if
an overridden method is invoked in a super constructor
or super class instance initialiser.
How could you instantiate a class without the static
initialisation having occurred (class
initialisation).
I thought it was obvious but the following one should be more so. Note that the class (nothing to do with an instance) is not initialized until the static initializer completes.
And again I want to point that if this happens in real code then the most likely reason is because of a bug or because the design is wrong. The chance of finding a legitimate reason to have code like this is zero in my mind.
public class TTest
public static void main(String[] args)
TTest()
System.out.println("Now in the constructor");
static
System.out.println("Start the static initializer");
reallyStupid();
System.out.println("End the static initializer");
static private boolean isDone;
private static void reallyStupid()
System.out.println("really stupid thing to do");
if (!isDone)
isDone = true;
TTest t = new TTest();
The output is...
Start the static initializer
really stupid thing to do
Now in the constructor
End the static initializer -
Pass parameter to Runnable invoked by SwingUtil.invokeLater()
Hi there,
I just got trapped by a Threading problem in my SwingApplet:
The Applet parses XML Documents it receives from a Servlet and dynamically creates a GUI from that description, using Swing Components. (actually Applet and Servlet exchange a Queue of JAVA Objects, each representing a fraction of the complete GUI Description or causing the Applet to show a certain URL, for example)
Getting the XML Documents is done in an extra Thread (not the EventDispatchThread), since that might take a while. For doing the actual update of the Swing Components I use SwingUtilities.invokeLater(Runnable doc).
doc is my internal Representation of the GUI, doc.run() does the actual Parsing and GUI Updating.
My Question is: How can I pass doc the Message it has to parse in a way that subsequent calls to invokeLater(doc) (which - as I mentioned - are done in another Thread) cannot disturb the processing of the previous call?
My actual (pseudo-)code tries it this way:
Executed in Calling Thread:
private void callSwing(PWDocumentGui doc)
try
Iterator it = fromserver.getInqueue().iterator();
while (it.hasNext())
PWMessage msg = (PWMessage) it.next();
doc.setContent(msg);
Thread.sleep(2000); // makes it work for the moment - but thats extremely unsafe!!
it.remove();
catch (Exception e)
System.err.println(e);
Internal Document representing the GUI:
class PWDocumentGui extends Observable implements Runnable
private InternalModel internalmodel; // holds internal Model of GUI (Arrays of Swing Components
private String onemessage; // holds one message to be parsed: VALUE IS THE PROBLEM !
public void synchronized setContent(String themessage)
onemessage = themessage; // remeber the Message to be parsed
SwingUtilities.invokeLater(this) // call this.run() in EventThtead
// Called in Event Thread
// value of onemessage in the meantime might be overwritten by subsequent call to setContent().
public void run()
// do the parsing into the local and thus update internalmodel
parse(onemessage);
// Notify Observers (the Renderers registered as Observers of this) that they should update themselves
// accordicg to internalmodel
setChanged()
notifyObservers();
public InternalModel getModel() { return internalmodel; }
I suspect that the solution might be easy - for someone more relaxed...
This might be a question concerning design, not Swing, I think.
Thanks for any answer!
UweTry creating an inner class which implements runnable.
Give the inner class members to hold the parameters you want to pass.
Implement the inner class's run() to check the variables and use them.
When calling invoke later create a new instance of the inner class, initialise the members for the parameter values and pass the inner class instance to invokeLater rather than the object of the main class.
In this way you get one copy of the parameters for every call to invoke later. -
About static variable initialization
Here is an exercise where you have to guess the output :-)
public class MyClass{
private static int x = getValue();
private static int y = 5;
private static int getValue(){
System.out.print("Running getValue ");
return y;
public static void main(String[] args){
System.out.println(x);
}This code outputs "Running getValue 0" I don't understand why?because class initialisation will call getValue() before it initialises 7 to 5, thus setting x to the value y has before being initialised which is 0.
What this tells you is that you should never program rubbish like that, and in general not rely on the value of uninitialised members. -
What is the difference between the usb charger, and the other one for micro
I bought the usb travel charger.:smileysurprised: What about the other one?
A compiled class has two concealed initialisation methods, class initialization <clinit> and instance initialization <init>.
These are created by concatenating initialisation blocks and initial value clauses associated with fields of the class in the order they appear in the source.
Class initialisation is performed the first time a class is "actively used", which means either by accessing a static field or member or by instanciating the class. It's performed first, and the initialisation methods are syncrhonized on the class, so that the class is effectively locked until it finishes.
The normal sequence of isntantiating the class is:
1) Call <clinit> if it hasn't been called.
2) Allocate the space for the instance and clear the fields to zero/null
3) Call <init>
4) Execute the constructor
<init> first calls super.<init> -
Use of static{};
I would like to ask a dummy Question.
class A{
static{
//something
in this program, the "static{};" is use for what?
THXHow is that different from a constructor?Because it's performed only once for the whole class, not for each instance you create (and even if you never create an instance). Consequently it can access only static variables and methods.
The java compiler creates two secret methods per class. <clinit> for class initialisation and <init> for instance intialisation. <clinit> is formed by gluing together all initialization of static fields, plus static blocks in the order they occur. Likewise <init> is formed by gluing together all the instance field initializers and any "instance initializer" blocks. You'll sometimes see these method names on stack traces. <clinit> is called automatically the first time you try to use the class, either creating and instance or accessing a static field or method. When the class is first loaded all fields are set to zero so any non-zero initial values are set at this point.
My favourite use for static {} is preloading static Map objects. -
Examples for good programming practice with multiple DAQmx tasks
I'm writing a program to continuously log data from 8 counters, 8 encoders, and 8 voltages. The proof of concept VI with a single counter was simple and elegant, but scaling up to all signals resulted in a wiring mess. I've been working through the Labview Core courses, and am currently on Core 3. I still haven't come across a discussion on how to work with multiple DAQmx tasks without making a mess of the block diagram. Can anyone point me in the right direction?
Also, say I have a state machine that has a configure, idle, and logging states. I need to set the initial values of the encoders during configuration, and keep up with their changes while in the idle state so I have appropriate starting values when entering the logging state. Can anyone point to an example that shows how this might be accomplished?
ThanksI'm very familiar with AE's/Functional Globals - but I have struggled in the past with handling multiple DAQmx tasks - particularly when you're using multiple devices and using different types of measurements which require seperate tasks/handling (e.g. such as thermocouples which require extra compensation).
I'm not even sure I know whare the requirements are for needing multiple tasks - I know you can need multiple tasks for a single device if the type of measurement is different but can you share an Analogue Input task amongst multiple devices?
I think in hindsight (and without too much thought now) it looks like a good case for Object Oriented LabVIEW - with a base DAQmx class (initialise, configure, start, acquire, stop, close etc.) and then child classes for each type of measurement (with one task associated with each - and private data unique to that specific class). You then hold an array of objects (one for each task) and iterate through each one with dynamic despatch to get the data.
I don't know your particular experience level of using LabVIEW (and as such, OO may not be appropriate) - but as a wider discussion of 'best practice' it seems like an appropriate method I would use going forward.
Certified LabVIEW Architect, Certified TestStand Developer
NI Days (and A&DF): 2010, 2011, 2013, 2014
NI Week: 2012, 2014
Knowledgeable in all things Giant Tetris and WebSockets -
Preloading dynamically created objects
Hi,
I have some Object I would like to create on runtime, but it initialization takes some time. So normally I would code something like
Class SimpleFoo
private BigObject bO = new bO("parameters here");
BigObject getBigObject()
return bO;
}but now I have a lot (say around 30 in the total class, which is more complicated) of them, so it would be something like
Class MessyFoo
private BigObject bOprime = new bO("prime parameters here");
private BigObject bOeven = new bO("even parameters here");
BigObject getBigObject(int i)
if (isPrime(i))
return bOprime;
else if (isEven(i))
return bOeven;
}which gets really messy. I'd rather code
Class CleanLookingFoo
BigObject getBigObject(int i)
if (isPrime(i))
return new bO("prime parameters here");
else if (isEven(i))
return new bO("even parameters here");
}but then I miss the caching and initialization advantages. What is the best way to build this? So far my best option is to pre-process the CleanLookingFoo and make a MessyFoo out of it, and then pass it through to the Java compiler, which probably isn't the best solution.The usual pattern is to use a synchronization mechanism and a lazy initialiser. The simplest mechanism is to use a holder class with a static field, since it won't get initialised until it's first used:
public class LazyBigObjects {
static class BigObject {
BigObject (String params) {
System.out.println(params);
static class PrimeBigObjectHolder {
static final BigObject INSTANCE = new BigObject("prime parameters here");
static class EvenBigObjectHolder {
static final BigObject INSTANCE = new BigObject("even parameters here");
public static BigObject getBigObject(int i) {
System.out.println("getBigObject called with " + i);
switch (i) {
case 0: {
return PrimeBigObjectHolder.INSTANCE;
case 1: {
return EvenBigObjectHolder.INSTANCE;
default:
throw new IllegalArgumentException(i + " out of range.");
public static void main (String...args) {
getBigObject(0);
getBigObject(1);
}Output:
getBigObject called with 0
prime parameters here
getBigObject called with 1
even parameters here
The JVM handles synchronisation issues of class initialisation, so you don't need to do anything about that. -
Difference between Developer provisioning profile and a Distribution one
With both a Developer provisioning profile and a Distribution Ad Hoc provisioning profile, an app can be installed on a designated device.
Is the only practical difference between the two kinds the fact that the Developer provisioning profile eventually expires?
Thanks,
dougA compiled class has two concealed initialisation methods, class initialization <clinit> and instance initialization <init>.
These are created by concatenating initialisation blocks and initial value clauses associated with fields of the class in the order they appear in the source.
Class initialisation is performed the first time a class is "actively used", which means either by accessing a static field or member or by instanciating the class. It's performed first, and the initialisation methods are syncrhonized on the class, so that the class is effectively locked until it finishes.
The normal sequence of isntantiating the class is:
1) Call <clinit> if it hasn't been called.
2) Allocate the space for the instance and clear the fields to zero/null
3) Call <init>
4) Execute the constructor
<init> first calls super.<init> -
MimeMessage.writeTo hangs on PipedInputStream.awaitSpace()
Hi all,
I have a multi-threaded app which (amongst other things) creates mail files and writes them to disk. When this app is under heavy load, I get several threads "left behind" which appear to be stuck on the call to awaitSpace() within the PipedInputStream class.
In debug, I notice that this method just loops around forever waiting for input. The problem is that I'm not controlling this. I'm just calling the writeTo(OutputStream) method of the MimeMessage class in JavaMail.
Goes something like this...
FileOutputStream fout = null;
try {
fout = new FileOutputStream("somefile.txt");
// Just a normal MimeMessage class initialised elsewhere
message.writeTo(out);
fout.flush();
finally {
if (fout != null) {
fout.close();
}This obviously works fine, but under heavy load the call to message.writeTo(out); blocks forever.
Not sure if it's a problem with the MimeMessage class or the PipedInputStream class (or my code?).
Anyone seen this behaviour before?
I'm using JDK 1.5.0_04Can you provide a stack trace for the thread that's stuck in PipedInputStream?
I believe the only time a PipedInputStream is used is when you try to
read data from a message part using getInputStream, but the message
part was created using an object instead of a stream so the JAF
DataContentHandler that converts objects to streams uses writeTo to
write the data into a PipedOutputStream so that you can read if from a
PipedInputStream. If you don't consume the entire stream, the writing
thread and the pipe will be left hanging.
If all you're doing is message.writeTo, I'm not sure why this would happen.
Maybe you are looking for
-
Start up disk full - doesn't add up!
Hi, I'm a first time Mac user and, I am having trouble with a full start up disc. My iMac 1 TB hard disc only has 12 GB unused space. I've seen a number of questions posted, so it seems I'm not the only one experiencing this problem. However I've not
-
Portable Home Directories over CIFS
I'm trying to configure PHD over CIFS with samba/linux as file server. It works. But there is a issue. When it synchronizes directory with server, for every newly created folder it complains about problem with sync.But regardless of complain director
-
Hi! I have a brand new Macbook Pro 13" Retina Display with i7. I bought it brand new from Apple for about 2 weeks ago and something wierd happens sometimes. The keyboard stops working, and the touchpad. I can not move the mouse, and I can not press a
-
Getting Error While recording F-32 thru LSMW
Dear All, I have recorded F-32 thru LSMW, it has recorderd successfully, problem is that while READING DATA system is showing an error. Generation cancelled. Reason: Syntax Errors Message no. /SAPDMC/LSMW_OBJ_070031 Pls help on this Regards Ranjit.
-
Webserver - "Failed to Connect to SBOCommon -111"
hi, i have a little web-application, that connects to the SAP-Db via DIApi. it worked fine on the test-server, but now in the live-environment it crashes from time to time (i can't login and get the error message mentioned above). After a restart of