Static nonstatic class object constructor

I was wonderring what is the use of non static constructors??
we all know about static constructors, they are used for initializing the class.
we all know about constructos, they are used for initializing an object from a given class.
what I dont know is the use of non static constructors such as this
class A{
     static{
          System.out.println ("Class A Static Constructor");
          /*What is the use of this???????
           *why dont we put this inside the constructor??
          System.out.println ("Class A NON static constructor");
     A(){
          System.out.println ("Class A Constructor");
class B extends A{
     static{
          System.out.println ("Class B static constructor");
          System.out.println ("Class B NON static Constructor");
     B(){
          System.out.println ("Class B Constructor");
public class Test{
     public static void main(String[]args){
          new B();
          new B();
}I would appreciate understaind this!! I can only see that if there was no other constructor, it can be used instead of the default constructor() with no arguments,
any clarification?

They are called static and non static intializer.
The non static initializer was introduced in the language subsequently with inner classes.
It's used the give an anonymous inner class a feature that behaves like a constructor (though with no args).
It's useless for other kinds of class.
abstract class A{
     A(){
          System.out.println("A constructor");
     abstract void exec();
class B{
     static A getA(){
          return new A(){
                         System.out.println("the cool implementation");
                    void exec(){
                         System.out.println("exec()");
     public static void main( String[] args){
          A a = B.getA();
          a.exec();
}Cut and paste in a new text file, call it B.java, then javac B.java, and java B.

Similar Messages

  • New class object statically.

    I have a class Test. This class has a static method which has as its purpose to create a new Test object. I currently have something like this:
    public static Test getInstance() {
      return new Test();
    }I was wondering if it is possible to write this code in such a way that no explicit reference to Test was made... and, as the always important follow up question, if it is possible, whether it is wise to do so?

    I have an interface and several classes implementing
    that interface. Each of these classes has a static
    method that has a Hashtable as a parameter. When that
    static method is called, the method creates an object
    of the class it is in and then adds the object to the
    Hashtable (the key for this entry is retrieved from
    the class its from).
    The 'problem' is that I have to write each of those
    methods in each class myself, when all I really want
    is to do the exact same thing over and over again
    (with each of the classes), just with different class
    objects.it's not "the same exact thing" over and over, though, is it? you're instantiating different classes in different methods. are you doing this to keep track of instances? you could have a factory that uses reflection to instantiate classes, and add them to the correct Map, but it can be awkward

  • Safe to synchronize on Class object?

    Is it considered safe and good practice for a method to synchronize on the Class object of it's own class? I am using lazy initialization for a static field; the field is initialized to null when the class is loaded and then set to its actual value the first time it is used. I need to make sure the actual initialization is thread safe. Here is a simplified example of what I am doing.
    public class Test {
        private static String myField = null;
        public String foo() {
            synchronized (Test.class) {
                if (myField == null) {
                    myField = "Hello world!";
            return myField;
    }It seems like that should work, but I was a little worried that by locking the Class object I might cause a problem with the class loader or something.

    jschell wrote:
    Nick_Radov wrote:
    I have to use lazy initialization rather than initializing the static field in clinit because it's value depends on a superclass field which isn't fully available until the class loader finishes loading the class. So the lazy initialization is just to get around that sequencing problem.Huh? That is certainly phrased oddly at best. If a "superclass" is used then it is fully loaded before it is used. There is no sequencing problem with that.He might have a design problem. He can se a partly initialized super class if that method is overridden and invoked by the parent constructor.
    Kaj

  • Abstract classes and Constructors

    I am wiondering how can an Abstract class have a constructor?
    Won't the constructor of the derived class
    automatically invoke the constructor of Shape
    by calling super()implicitly
    That means that an object of type Shape has been created
    Or have I overlooked a certain point?
    abstract class Shape {
         public String color;
         public Shape() {
         public void setColor(String c) {
              color = c;
         public String getColor() {
              return color;
         abstract public double area();
    public class Point extends Shape {
         static int x, y;
            // ?? Wont this constructor invoke the super class's constructor?
         public Point() {
              x = 0;
              y = 0;
         public double area() {
              return 0;
         public static void print() {
              System.out.println("point: " + x + "," + y);
         public static void main(String args[]) {
              Point p = new Point();
              p.print();
    }

    bhuru_luthria wrote:
    I am wiondering how can an Abstract class have a constructor?
    Won't the constructor of the derived class
    automatically invoke the constructor of Shape
    by calling super()implicitly If you don't explicitly invoke a superclass c'tor, super() will be called, but you can also explicitly invoke any non-private parent constructor from the child's constructor.
    That means that an object of type Shape has been createdC'tors don't create objects. They initialize newly created objects to valid state.

  • About Class Object  as Array

    Hello.. I'm beginner in Java Programming
    Now i learn about Array.. i'm not understand about use class object become array. for example i'm create class object Card.
    Then i call Card object to CardTest as main object and Card object called as array.
    can you tell me about how to work Card object as array in CardTest ?
    Edited by: 994075 on Mar 14, 2013 11:55 PM

    994075 wrote:
    yup..thanks guru :DI'm no guru, I just bought a decent Java book 10 years ago and here I am.
    so i guess Object Class can be array :).I don't get that statement. You can store objects in an array, if that's what you mean. An array itself is also an object.
    but i'm not understrand if static method in Card object can be called automatically when Card initialized in CardTest?a) research constructors
    b) you usually don't need static methods, its just something that people new to the language tend to overuse because then you don't have to create object instances. Forget about static methods, try to make it work using regular non-static methods.
    And you really should read and study more, you're coming to the forum way too soon. First get a solid knowledge base, the only thing you're doing now is asking questions that you could have answered for yourself by studying more.

  • A question about non-static inner class...

    hello everybody. i have a question about the non-static inner class. following is a block of codes:
    i can declare and have a handle of a non-static inner class, like this : Inner0.HaveValue hv = inn.getHandle( 100 );
    but why cannot i create an object of that non-static inner class by calling its constructor? like this : Inner0.HaveValue hv = Inner0.HaveValue( 100 );
    is it true that "you can never CREATE an object of a non-static inner class( an object of Inner0.HaveValue ) without an object of the outer class( an object of Inner0 )"??
    does the object "hv" in this program belong to the object of its outer class( that is : "inn" )? if "inn" is destroyed by the gc, can "hv" continue to exist?
    thanks a lot. I am a foreigner and my english is not very pure. I hope that i have expressed my idea clearly.
    // -------------- the codes -------------------
    import java.util.*;
    public class Inner0 {
    // definition of an inner class HaveValue...
    private class HaveValue {
    private int itsVal;
    public int getValue() {
    return itsVal;
    public HaveValue( int i ) {
    itsVal = i;
    // create an object of the inner class by calling this function ...
    public HaveValue getHandle( int i ) {
    return new HaveValue( i );
    public static void main( String[] args ) {
    Inner0 inn = new Inner0();
    Inner0.HaveValue hv = inn.getHandle( 100 );
    System.out.println( "i can create an inner class object." );
    System.out.println( "i can also get its value : " + hv.getValue() );
    return;
    // -------------- end of the codes --------------

    when you want to create an object of a non-static inner class, you have to have a reference of the enclosing class.
    You can create an instance of the inner class as:
    outer.inner oi = new outer().new inner();

  • How to tell if a Class object is instantiable at run time ?

    Hi
    Newbie here, I am making some modification to an existing code and need to tell if
    a Class object can be instantiated. My specific object is an abstract class.
    I found I can ask if a Class is an interface via
    Class class = ...;
    if (class.isInterface())
    but could not find anything for abstract classes. Any idea ? Thanks

    baftos wrote:
    Modifier.isAbstract(clazz.getModifiers())Edited by: baftos on May 30, 2009 9:38 AMThis only covers the case of an abstract class. Below is a more robust solution. However even this solution has gaps - For instance, it is definitely possible to instantiate a URL object, but you've kind of got to know how to do it if you want to avoid a malformedURLException. If we are just talking about being able to instantiate the default constructor, this will suffice
    package tjacobs.test;
    import java.lang.reflect.Constructor;
    public class Test {
         public static class Bar {
              public static void install() {
              public Bar() {}
         public static abstract class Foo {
              public static void install() {
              public Foo() {}
         public static class FooBar {
              public static void install() {
              private FooBar() {}
         public static void abstractTest() {
    //          Foo.install();
    //          Bar.install();
    //          FooBar.install();
              abstractTest("tjacobs.test.Test");
              abstractTest("tjacobs.test.Test$Foo");
              abstractTest("tjacobs.test.Test$Bar");
              abstractTest("tjacobs.test.Test$FooBar");
         public static void abstractTest(String str) {
              Class c = null;
              try {
                   c = Class.forName(str);
              catch (Exception ex) {
                   ex.printStackTrace();
              try {
                   Constructor con = c.getConstructor(new Class[] {});
                   Object obj = con.newInstance(new Object[] {});
                   System.out.println("Can instatiate");
              catch (Exception ex) {
                   System.out.println("Cannot instantiate!");
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              abstractTest();
    }

  • Object Constructors

    Well, I heard this from my "Object Oriented Programming, Distributed Computing, and Web Services" teacher:
    A constructor cannot call any method on it's code. Of course you can code-it to call te method, but it would be bad OO programming. Is that true? If so... ALL JAVA OBJECT CONSTRCUTORS WORK THAT WAY
    ( java.util.LinkedList.LinkedList(java.util.Collection clct),
    java.util.StrinkTokenizer.StringTokenizer(java.util.String str),
    java.lang.Integer(int value), as some examples...) ???
    THNX

    mm.. I but I'm not talking about invoking methods like
    utilities or something, but 2initializer methods".. I
    dunno, but I wrote the LinkedList(Collections cl)
    example.. how does the constructor works... would it
    be possible it calls a method who parses the
    collection to a LinkedList, or in any other example, I
    hava a Traingle Class with a constructor which
    receives 3 int arguments one for each side, for
    example you give negative parameters, or arguments
    which cannot create a real Triangle (they dissmatch
    when drawing it, for example) could you call a
    validation method?? or just create it?? Yes it's perfectly fine to create a method to be called by the constructor. Often it's the only good design choice.
    As mentioned above, you should avoid calling non-final, non-private, non-static methods from the constructor of a class. You can't be sure what the method will do or whether it will execute successfully. There is more to this issue than just that but if you find that you need to call an abstract or non-final method from a constructor, you consider refactoring the class using a Factory method or the AbstractFactory pattern.
    But there should be no major problems calling private or final or static methods.

  • Why do we intialize other classes in constructor ????

    Please see the question below:
    class MThread extends Thread {
    private Abc mfact = null;
    private Xyz mo = null;
    private Pro sts = null;
    * Constructor.
    public MThread(Abc mfact, Xyz mo ) { *// do i have to pass Pro here from calling method so that i can initialize in constructor in order to use its method like record ???*
    this.mfact = mfact;
    this.mo = mo;
    public somemethod() {
    sts.record();
    public void somemethod1() {
    mo.create();
    ***************************************************Another Class******************************************************
    public class Xyz{
    // Some code here
    // this class calls Mthread and creates 10 such Threads sth like
    for (int i = 0; i < 10; i++) {
    mThreads[i] = new MThread(mfact, mo;
    ***********Another Class ****************
    public class Pro {
    // some code
    public synchronized record() {
    rat ++;
    Explanation :
    Xyz calls Mthread 10 times to create such threads.
    Mthread has method that class Pro for stats recording
    Mthread also uses other class files to do some functioning of its own.
    Question:
    Please see the question in the constructor of Mthread ??
    for using method like record in Pro. do i have to initialize that in the constructor of Mthread ??
    because other class like Abc initializes itself in the construtor??
    Why do we have to initialize some class in constructor ?? I don't get it ?? Also when i press F3 (Open declaration ) on record call in somemethod ()
    .. it properly opens the file of class Pro and points to my sychronized method in that class ??
    CONFUSED... Please help ..
    Thank you

    javanewbie83 wrote:
    To morgair:
    thats right..so actually my question was do i need to change the requiremensts of the constructor so i can pass in the value of class Pro from the calling method.
    Do i need to do that. is that compulsory to use one of its methods
    ThanksYes, somehow you have to get visibility to your object that you want to use. If it's not passed in, then you have to have it in some global context with reference to where you want to use it.
    class myClass{
      A a;
      B b;
      C c;
      myClass(A a, B b, C c){
        this.a = a;
        this.b = b;
        this.c = c;
      public void myMethod(){
        c.doSomething(a, b);
    // This can be done since a and b are supplied as arguments to the constructor
    // but also consider this:
    class myClass{
      A a;
      B b;
      C c;
      myClass(A a, B b){
        this.a = a;
        this.b = b;
        c = new C();
      public void myMethod(){
        c.doSomething(a, b);
    //this will also work but c is a local variable
    //also consider this:
    class myOuterClass{
      A a;
      B b;
      C c;
      myOuterClass(){
        a = new A();
        b = new B();
        c = new C();
        //do stuff
      public void someStuff(){ 
        myInnerClass p = new myInnerClass(a, b);
        p.myMethod();  //this will also work since c is defined in myOuterClass
      class myInnerClass{
        A a;
        B b;
        myInnerClass(A a, B b){
          this.a = a;
          this.b = b;
        public void myMethod(){
          c.doSomething(a, b);
    }Note: this example is supplied off the top of my head without being tried in my IDE, but should show the concepts even if my fat fingers have hit the wrong keys.

  • Casting base class object to derived class object

    interface myinterface
         void fun1();
    class Base implements myinterface
         public void fun1()
    class Derived extends Base
    public class File1
         public myinterface fun()
              return (myinterface) new Base();
         public static void main(String args[])
              File1 obj = new File1();
              Derived dobj = (Derived)obj.fun();
    Giving the exception ClassCastException......
    Can't we convert from base class object to derived class.
    Can any one help me please...
    Thnaks in Advance
    Bharath kumar.

    When posting code, please use tags
    The object returned by File1.fun() is of type Base. You cannot cast an object to something it isn't - in this case, Base isn't Dervied. If you added some member variables to Derived, and the compiler allowed your cast from Base to Derived to succeed, where would these member variables come from?
    Also, you don't need the cast to myinterface in File1.fun()
    Also, normal Java coding conventions recommend naming classes and interfaces (in this case, myinterface) with leading capital letters, and camel-case caps throughout (e.g. MyInterface)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Using Class and Constructor to create instances on the fly

    hi,
    i want to be able to create instances of classes as specified by the user of my application. i hold the class names as String objects in a LinkedList, check to see if the named class exists and then try and create an instance of it as follows.
    the problem im having is that the classes i want to create are held in a directory lower down the directory hierarchy than where the i called this code from.
    ie. the classes are held in "eccs/model/behaviours" but the VM looks for them in the eccs directory.
    i cannot move the desired classes to this folder for other reasons and if i try to give the Path name to Class.forName() it will not find them. instead i think it looks for a class called "eccs/model/behaviours/x" in the eccs dir and not navigate to the eccs/model/behaviours dir for the class x.
    any ideas please? heres my code for ye to look at in case im not making any sense:)
    //iterator is the Iterator of the LinkedList that holds all the names of the
    //classes we want to create.
    //while there is another element in the list.
    while(iterator.hasNext())
    //get the name of the class to create from the list.
    String className = (String) iterator.next();
    //check to see if the file exists.
    if(!doesFileExist(className))
    System.out.println("File cannot be found!");
    //breake the loop and move onto the next element in the list.
    continue;
    //create an empty class.
    Class dynamicClass = Class.forName(className);
    //get the default constructor of the class.
    Constructor constructor = dynamicClass.getConstructor(new Class[] {});
    //create an instance of the desired class.
    Behaviour beh = (Behaviour) constructor.newInstance(new Object[] {});
    private boolean doesFileExist(String fileName)
    //append .class to the file name.
    fileName += ".class";
    //get the file.
    File file = new File(fileName);
    //check if it exists.
    if(file.exists())
    return true;
    else
    return false;
    }

    ok ive changed it now to "eccs.model.behaviours" and it seems to work:) many thanks!!!
    by the following you mean that instead of using the method "doesFileExist(fileName)" i just catch the exception and throw it to something like the System.out.println() ?
    Why don't you simply try to call Class.forName() and catch the exception if it doesn't exist? Because as soon as you package up your class files in a jar file (which you should) your approach won't work at all.i dont think il be creating a JAR file as i want the user to be able to create his/her own classes and add them to the directory to be used in the application. is this the correct way to do this??
    again many thanks for ye're help:)

  • Loading and viewing XML when a class object is created..Help Please

    Hello,
    I have writing a simple class which has a method that gets invoke when the object of the class is created. I am able to view the loaded XML content when I trace it with in my class method, but cannot assign the content to a instance variable using the mutator method. So the process goes like this:
    Class object is instantiated
    Class construtor then calls the loadXML method which laods the XML
    And then assigns the XML to a class instance variable.
    So now if I would like to access the loaded XML through class object, I should be able to see the loaded xml content which I am not able to see. I have spent over few hours and cannot get the class object to display the loaded XML content. I would highly appreciate it if someone can help in the right direction, please.
    [code]
    package com.as3.app
        import flash.display.*;
        import flash.events.*;
        import flash.text.*;
        import flash.net.*;
        public class Cars extends MovieClip {
               public var _CarList:Object;
               public function Quiz()
                  super();
                  loadCars();
    // ===========================================================
    //           CARS GETTER SETTER
    // ===========================================================
            public function set Cars(val:XML):void
                this._CarList = val;
            public function get Cars():XML
                return this._CarList;
    // ===========================================================
    //            LOAD QUESTIONS FROM XML
    // ===========================================================
            public function loadcars()
                var myXML:XML;
                var myLoader:URLLoader = new URLLoader();
                myLoader.load(new URLRequest("xml/cars.xml"));
                myLoader.addEventListener(Event.COMPLETE, processXML);
                function processXML(e:Event):void
                    myXML = new XML(e.target.data);  
                    Cars = myXML;                 // Assigning the loaded xml data via mutator method to the _CarList;
    //=============================================================  
                                  INSTANTIATING THE CLASS OBJECT
    //=============================================================
    package com.as3.app
        import flash.display.*;
        import flash.events.*;
        import flash.text.*;
        import flash.net.*;
        import com.as3.app.*;
        public class DocumentClass extends MovieClip {
            public var c:Car;
            public function DocumentClass()
                super();
                c = new Cars();  
                trace(c.Cars);
    [/code

    where you have:
                super();
                c = new Cars();  
                trace(c.Cars);
    c.Cars will not trace as the loaded xml, because it will not have loaded in time. After some time it should presumably have the correct value.
    loading operations in actionscript are asynchronous, so your nested function which is acting as the listener ( function processXML(e:Event):void) only ever executes when the raw xml data has loaded and that is (I believe, not 100% sure) always at least one frame subsequent to the current one.
    In general I would consider it bad practise to use nested functions like that, but I don't think its contributing to your issues here. I think its just a timing issue given how things work in flash....
    Additional observation:
    your Cars constructor calls loadCars() and your loadCars method is defined as:
    public function loadcars()
    I assume its just a typo in the forum that the uppercase is missing in the function name....

  • Which one is better static inner classes or inheritance ?

    Hi,
    Consider following scenario,
    Class A does some database related work and Class B,C,D has more specific tasks for specific databases. For now B,C,D has more static information like driver name etc.
    1. I can either make class B,C,D as static inner classes OR
    2. classes B,C,D can extend class A.
    Case 1. makes it more flexible, if in future, B,C,D needs more than static methods.
    Case 2. can avoid complexity and cost of instantiating differnt objects based on differnt scenarios.
    Which approache is better in both ?
    Thanks

    Yes, I have seen abstract factory pattern , rather I have implemeted it at one place and in case 1. using abstract factory pattern is the way to initialize all classes.But my question is if I make all subclasses as a static inner classes, will it be better or efficient approach as compare to abstract factory pattern.Because Abstract factory patter adds more complications in code in turn it provides more flexibility.

  • BUG: Oracle Java Compiler bug with anonymous inner classes in constructor

    The following code compiles and runs just fine using 1.4.2_07, 1.5.0_07 and 1.6.0_beta2 when compiling and running from the command-line.
    It does not run when compiling from JDeveloper 10.1.3.36.73 (which uses the ojc.jar).
    When compiled from JDeveloper, the JRE (both the embedded one or the external 1.5.0_07 one) reports the following error:
    java.lang.VerifyError: (class: com/ids/arithmeticexpr/Scanner, method: <init> signature: (Ljava/io/Reader;)V) Expecting to find object/array on
    stack
    Here's the code:
    /** lexical analyzer for arithmetic expressions.
    Fixes the lookahead problem for TT_EOL.
    public class Scanner extends StreamTokenizer
    /** kludge: pushes an anonymous Reader which inserts
    a space after each newline.
    public Scanner( Reader r )
    super( new FilterReader( new BufferedReader( r ) )
    protected boolean addSpace; // kludge to add space after \n
    public int read() throws IOException
    int ch = addSpace ? ' ' : in.read();
    addSpace = ch == '\n';
    return ch;
    public static void main( String[] args )
    Scanner scanner = new Scanner( new StringReader("1+2") ); // !!!
    Removing the (implicit) reference to 'this' in the call to super() by passing an instance of a static inner class 'Kludge' instead of the anonymous subclass of FilterReader fixes the error. The code will then run even when compiled with ojc. There seems to be a bug in ojc concerning references to the partially constructed object (a bug which which is not present in the reference compilers.)
    -- Sebastian

    Thanks Sebastian, I filed a bug for OJC, and I'll look at the Javac bug. Either way, OJC should either give an error or create correct code.
    Keimpe Bronkhorst
    JDev Team

  • How can I call a nonstatic class

    Hello All,
    I've wrote a simple bean for my testcase that count a value (e.g. site access):
    public class Bean1 {
    private int accessCount = 1;
    public int getAccessCount() {
    return (accessCount++);
    If I call the bean with a jsp-site, it works fine with different scope. e.g. session and application.
    With session scope different browser count different. With application scope different bowser count together. Thats the normal attitude.
    My jsp code:
    <jsp:useBean id="counter" class="ml.view.Bean1" scope="session" />
    <jsp:getProperty name="counter" property="accessCount" />
    This don't work with a static bean (normal too), but I can only call a static class in my UIX site.
    I call the bean from uix with the invoke element. Is that correct? How can I call a nonstatic class with a special scope? Which other solution ist possible?
    My uix code:
    <invoke method="getAccessCount" result="${uix.eventResult.getAccessCount}" instance="${sessionScope.myBean.getAccessCount}" exception="${uix.eventResult.error}" javaType="ml.view.myBean"/>
    Thank you for any solution!
    The error messages are:
    java.lang.NullPointerException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java)
    at oracle.cabo.servlet.event.InvokeEventHandler._invoke(Unknown Source)
    at
    and so forth...

    false in my uix code example: javaType="ml.view.myBean"
    correct: javaType="ml.view.Bean1"
    Sorry :-) that was only an error in my post not in the really example.

Maybe you are looking for