免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1245 | 回复: 0
打印 上一主题 下一主题

Thinking in java -- Initialization & Cleanup [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-07-17 09:14 |只看该作者 |倒序浏览

               
               
               
               
               
               
                    C++ introduced the concept of a constructor, a special method automatically called when an objects is created. Java also adopted the constructor, an in additon has a garbage collector that automatically releases memory resources when they're no longer being used.
Guaranteed initialization with the constructor
    In Java, the class designer can guarantee initialization of every object by providing a special method called a constructor. The name of the constructor is the same as the name of the class. It makes sense that such a method will be called automatically on initialization. Like any method, the constructor can have arguments to allow you to specify how an object is created.
    The constructor is an unusual type of method because it has no return value. This is distinctly different from a void return value, in which the method returns nothing bu you still have the option to make it return something else. Constructors return nothing and you don't have an option (the new expression does return a reference to the newly-created object, but the constructor itself has no return value).
Method overloading
    In Java, another factor forces the overloading of method names: the constructor. Because the constructor's name is predetermined by the name of the class, there can be only one constructor name. method overloading is essential to allow the same method name to be used with different argument types. And although method overloading is a must for constructors, it's a general convenience and can be used with any method.
  Distinguishing overloaded methods
    Each overloaded method must take a unique list of argument types. Even differences in the ordering of arguments are sufficient to distinguish two methods.
  Overloading with promitives
    A primitive can be automatically promoted from a smaller type to a larger one and this can be slightly confusing in combination with overloading. If your argument is wider then you must cast to the necessary type using the type name in parentheses.
  Overloading on return values
    You can not use return value types to distinguish overloaded methods. For example, thest two methods, void f(){} and int f(){},  which have the same name and arguments, are easily distinguished from each other. But if you call the method this way f(); How can Java determine which f() should be called?
  Default constructors
    As mentioned previously, a default cosntructor is one without arguments, used to create a "basic object." If you create a class that has no constructors, the compiler will automatically create a default constructor for you. However, if you define any constructors (with or without arguments), the compiler will not synthesize for you. That's to say, if you defined all constructors with arguments, and now if you say: new ClassName(); the compiler will complain that it cannot find a constructor that matches.
  The this keyword
    The this keyword --- which can be used only inside a method --- produces the reference to the object the method has been called for. The this keyword is used only for those special cases in which you need to explicitly use the reference to the current object. for example, it's often used in return statements when you want to return statements when you want to return the reference to the current object.
    Calling constructor from constructor
    In a constructor, the this keyword takes on a different meaning when you give it an argument list: it makes an explicit call to te constructor that matches that argument list. While you can call one constructor using this, you cannot call two. In addition, the constructor call must be the first thing you do or you'll get a compiler error message.
    The meaning of static
    There is no this for the static method. You cannot call non-static methods from inside static method (although the reverse is possible), and you can call a static method for the class itself, without any object.
Cleanup: finalization and garbage collection
    The garbage collector knows only how to release memory allocated with new, so it won't know how to release the object's "special" memory. When the garbage collector is ready to release the storage used for your object, it will first call finalize(), and only on the next garbage-collection pass will it reclaim the object's memory. It is important to distinguish between C++ and Java here, because in C++ objects always get destroyed (in a bug-free program), whereas in Java objects do not always get garbage-collected. or put another way:
    1. Your objects might not get garbage-collected.
    2. Garbage collection is not destruction.
  What is finalize() for?
    A third point to remember is:
    3. Garbage collection is only about memory.
    It would seem that finalize() is in place because of the possibility that you'll do something C-like by allocating memory using a mechanism other than the normal one in Java.
Member initialization
    Java goes out of its way to guarantee that variables are properly initialized before they are used. In the case of variables that are defined locally to a method, this guarantee comes in the form of a compile-time error. Forcing the programmer to provide an initialization value is more likely to catch a bug. If a primitive is a field in a class, however, things are a bit different. Each primitive field of a class is guaranteed to get an initial value. When you define an object reference inside a class without initializing it to a new object, that reference is given a special value of null.
  Specifying initialization
    One direct way to do specifying initialization is simply to assign the value at the point you define the variable in the class. You can also initialize nonprimitive objects in this same way.
  Constructor initialization
    There's one thing to keep in mind, however: you can't precluding the automatic initialization, which happens before the constructor is entered.
    Order of initialization
    Within a class, the order of initialization is determined by the order that the variables are defined within the class. The variable definitions may be scattered throughout and in between method definitions, but the variables are initialized before any methods can be called - even the constructor.
    Static data initialization
    When the data is static the same thing happens; if it's a primitive and you don't initialize it, it gets the standard primitive initial values. If it's a reference to an object, it's null unless you create a new object and attach your reference to it.
    If you want to place initialization at the point of definition, it looks the same as for non-statics.
    The static initialization occurs only if it's necessary. They are initialized only when the first object is created (or the first static access occurs). After that, the static objects are not reinitialized.
    It's helpful to summarize the process of creating an object. Considera class called Dog:
  • The first time an object of type Dog is created (the constructor is actually a static  method), or the first time a static method or static field of class Dog is accessed, the Java interpreter must locate Dog.class, which it does by searching through the classpath.
  • As Dog.class is loaded, all of its static initializers are run. Thus, static initialization takes place only once, as the Class object is loaded for the first time.
  • When you create a new Dog(), the construction process for a Dog object first allocates enough storage for a Dog object on the heap.
  • This storage is wiped to zero, automatically setting all the primitives in that Dog object to their default values (zero for numbers and the equivalent for boolean and char) and the references to null.
  • Any initializations that occur at the point of field definition are executed.
  • Constructors are executed. This might actually involve a fair amount of activity, especially when inheritance is involved.
        Explicit static initialization
        Java allows you to group other static initializations inside a special "static clause" (sometimes called a static block) in a class. It looks like this:
        class Spoon {        static int i;        static {            i = 47;        }    }
        It appears to be a method, but it's just the static keyword followed by a block of code. This code, like other static initializations, is executed only once, the first time you make an object of that class or the first time you acces a static member of that class(even if you never make an object of that class).
        Non-static instance initialization
        Java provides a similar syntax for initializing non-static variables for each object. It looks exactly like the static initialization clause except for the missing static keyword. This syntax is necessary to support the initialization of anonymous inner classes.
    Array initializationP(247)


    本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/8554/showart_141518.html
  • 您需要登录后才可以回帖 登录 | 注册

    本版积分规则 发表回复

      

    北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
    未成年举报专区
    中国互联网协会会员  联系我们:huangweiwei@itpub.net
    感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

    清除 Cookies - ChinaUnix - Archiver - WAP - TOP