Java key points of knowledge

Source: Internet
Author: User
Tags export class

Except for the static method and the final method in 1.Java, all other methods are dynamically bound, like the virtual functions of C + +, but we do not need to display the declarations.

The private method is essentially the final method (and therefore cannot be accessed by the Quilt Class).

A constructor is essentially a static method, except that the static declaration is implicit.

The final method causes the compiler to generate more efficient code, which is why declaring the final method can improve performance to some extent (the effect is not obvious).

If a method is static, its behavior is not polymorphic.

Calling a function that has polymorphic behavior inside a parent class constructor will result in unpredictable results, because the subclass object is not initialized at this time, and calling the subclass method will not get the result we want.

Only non-private methods can be overridden, but overriding the private method is a new method, not an overloaded method, for a subclass. Therefore, in a subclass, the new method name is best not to take the same name as the private method of the base class.

The access operations for Domains in the Java class are parsed by the compiler and are therefore not polymorphic. Properties with the same name as the parent and child classes are assigned different storage spaces. In order to get the attribute field of the parent class, you must explicitly indicate Super.field.

2.is-a relationship and Is-like-a relationship

Is-a relationships are pure inheritance, meaning that only methods that have been established in the base class can be overridden in subclasses. The base class and subclass have exactly the same interface, so when you are transitioning upward you never need to know the exact type of the object being processed, which is accomplished by polymorphism.

IS-LIKE-A Relationship: Subclasses extend the base class interface. It has the same basic interface, but he also has other features that are implemented by additional methods. The disadvantage is that the extensions of the interfaces in the subclass cannot be accessed by the base class, so the new methods cannot be called once the transformation is up.

Has-a Relationship: A class contains a reference to another class or interface.

Call order of constructors in 3.Java

A. Before anything else happens, initialize the storage space allocated to the object to binary 0.

B. Call the base class constructor.

C. Initialize methods that invoke members in the order they are declared.

D. Finally call the constructor of the subclass.

Because of the presence data, the actual process is

B. Initialization of all static members of the inheritance system (late Father class, later subclass)

C. Initialization of the parent class (initialization of the normal member---the call of the constructor)

D. Subclass initialization (normal member---constructors)

4. Run-time type information (RTTI + reflection)

RTTI: Run-time type information allows you to discover and use type information while the program is running.

How Java allows us to identify objects and class information at runtime, mainly in 3 ways

"Traditional" RTTI, which assumes that we already know all the types at compile time, such asShape s = (Shape)s1;

The "reflection" mechanism, which runs the information we discover and use classes at run time, is used Class.forName() .

Keyword instanceof , which returns a bool value, which keeps the concept of type, it refers to "are you the class?" Or are you a derived class of this class? ”。 If you compare the actual class object with = = or equals, there is no consideration for inheritance-it is either the exact type, or not.

To understand how Rtti works in Java, you must first know how the type information is represented at run time, which is done by a special object called, which Class对象 contains information about the class. Java sends a class object to perform its rtti, using the class loader's subsystem implementation.

Whenever you want to use type information at run time, you must first obtain a reference to the appropriate class object, which can be obtained in three ways:

A. If you do not have an object of this type, Class.forName() it is a convenient way to implement this feature because it does not require object information.

B. If you already have an object of the type of interest, you can call the getClass() method to get the class reference, which returns a class reference that represents the actual type of the object.

C. Use class literal constants. Like this: String.class; to quote.

This is not only simpler, but also more secure because it is checked at compile time (so it does not need to be placed in a try statement block), and it eliminates references to the Forname method and is therefore more efficient. Class literal constants can be applied not only to ordinary classes, but also to interfaces, arrays, and basic data types.

Attention:

When you use ". Class" To create a reference to a class object, the class object is not automatically initialized. Initialization is deferred until the first reference is made to a static method (the constructor is implicitly static) or to a non-final static domain (note that the final static domain does not trigger an initialization operation).

When using Class.forName, it is automatically initialized.

The preparation to use the class actually consists of three steps:

-Load: Executed by the ClassLoader. Find the bytecode and create a class object from these bytecode

-Link: Validates the bytecode in the class, allocates storage space for the static domain, and, if necessary, resolves all references to other classes created by this class.

-Initialize: If the class has a superclass, initialize it, execute static initializers, and static initialization blocks.

If you do not know the exact type of an object, Rtti can tell you, but there is a limit: This type must be known at compile time to recognize it using RTTI, which means that at compile time, the compiler must know all classes to be handled by RTTI. If you want to break this limit you need to use a reflection mechanism.

The principle of reflection:

ClassClasses java.lang.reflect support the concept of reflection along with the class library, which contains Field , Method as well as Constructor classes (each class implements an Member interface). These types of objects are created by the JVM at run time to represent the corresponding members in the unknown class. This allows you to use a method to invoke the method associated with the object by Constructor creating a new object, using get()/set() methods to read and modify the Field fields associated with the object invoke() Method . In addition, it is possible to invoke getFields()、getMethods()和getConstructors() an array of objects that represent fields, methods, and constructors, as well as convenient methods. In this way, the class information of an anonymous object can be fully determined at run time, and there is no need to know anything at compile time.

The difference between reflection and Rtti

When dealing with an object of unknown type through reflection, the JVM simply examines the object to see which particular class it belongs to (like Rtti), and must load the object of that class before doing anything else, Class so that class's .class Files must be available to the JVM: either on the local machine or on the network. So the real difference between Rtti and reflection is only: for Rtti, The compiler opens and checks the. class file at compile time (that is, all methods that can invoke the object in a normal way), and for the reflection mechanism, the. class file is not available at compile time, so the. class file is opened and checked at run time.

5. Proxy mode vs. dynamic Proxy in Java

Proxy mode
At any moment, as long as you want to separate the extra operations from the "real" objects into different places, especially when you want to be able to make changes easily, from not using extra actions to using them, or vice versa, the proxies are useful (the key to design patterns is encapsulation modifications). For example, what should you do if you want to keep track of calls to methods in a class, or if you want to measure the overhead of these calls? The code is definitely the code you don't want to incorporate into your app, so the proxy makes it easy to add or remove them.

Dynamic Agent
The dynamic agent of Java is a step closer to the idea of a proxy because it can dynamically create proxies and dynamically handle calls to proxy methods.

Test code

ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method;ImportJava.lang.reflect.Proxy;InterfaceInterface {voiddosomething (); voidSomethingElse (String arg);}classRealobjectImplementsInterface {@Override Public voiddosomething () {System.out.println ("[Realobject]dosomething.]); } @Override Public voidSomethingElse (String Arg) {System.out.println ("[Realobject]somethingelse:" +Arg); }}classDynamicproxyhandlerImplementsInvocationhandler {PrivateObject Mproxy;  PublicDynamicproxyhandler (Object proxy) {Mproxy=proxy; } @Override Publicobject Invoke (Object proxy, Method method, object[] args)throwsthrowable {System.out.println ("Proxy class:" +Proxy.getclass ()); System.out.println ("Method:" + Method + ". Args: "+args);        System.out.println (); if(Args! =NULL) {             for(Object Arg:args) System.out.println (" " +Arg); }        returnMethod.invoke ( This. Mproxy, args); }}classSimpledynamicproxy { Public Static voidconsumer (Interface iface) {iface.dosomething (); Iface.somethingelse (haha); }     Public Static voidMain (string[] args) {Realobject real=NewRealobject ();        Consumer (real); System.out.println ("--Insert a proxy and call again--"); Interface Proxy=(Interface) proxy.newproxyinstance (Interface.class. getClassLoader (),NewClass[] {Interface.class},NewDynamicproxyhandler (real));    Consumer (proxy); }}

Results

[Realobject]dosomething. [Realobject]somethingelse: Haha--Insert a proxy and call again--Proxyclass:class$Proxy 0method: Public Abstract voidInterface.dosomething (). ArgsNULL[Realobject]dosomething.proxyclass:class$Proxy 0method: Public Abstract voidInterface.somethingelse (java.lang.String). args: [ljava.lang.object;@6adcc4e2 haha [realobject]somethingelse: haha 

6. Access Control permissions

Java access modifiers: public, Protected, package access (default access rights, sometimes called friendly), and private.

Package access: All other classes in the current package have access to that member, but for all classes outside of the package, this member is private.

Protected: Inherit access rights. Protected gives the base class certain member access rights to the derived class. Protected also provides package access, which means that other classes within the same package can access the protected element. Protected indicates that this is private to the class user, but it is accessible to any export class that inherits from this class or any other class that is within the same package.

7. Selection between combinations and inheritance

Both combination and inheritance allow child objects to be placed in a new class, and the combination is explicitly done, whereas inheritance is implicitly done.

Combinatorial techniques are typically used in situations where you want to use the functionality of an existing class in a new class rather than its interface. is to embed an object in the new class to implement the functionality that is required, but the new class's users see only the interface defined for the new class, not the interface of the embedded object. To achieve this effect, you need to embed a private object of an existing class in the new class. Sometimes, however, it is very meaningful to allow users of a class to access the composition components of a new class directly, declaring the member object as public. This is safe if the member object itself hides a specific implementation. When the user is able to understand that you are assembling a set of parts, it makes the port easier to understand. For example, a car object can be combined by a public engine object, a wheel object, a Window object, and a door object. But be sure to remember that this is only a special case, in general, the domain should be made private.

At the time of inheritance, use an existing class and develop a special version of it. Typically, this means that you are using a generic class and specialize it for a particular need. A little thought will reveal that it makes no sense to use a "vehicle" object to form a "car", because "the car" does not contain "transport", it is only a means of transport (is-a relationship).

The relationship of "is-a" (is a) is expressed by inheritance, while the relationship of "has-a" (one) is expressed by a combination.

In the end is the use of combination or inheritance, one of the clearest way to judge is to ask yourself whether you need to change from the new class to the base class, the need to use inheritance, do not need to use the combination.

8.final keywords

When the final decoration is a basic data type, it refers to a constant number of values (that is, compile-time constants, if the static final decoration, it is emphasized only one copy), and the object reference instead of the basic type of final, its meaning is a little confusing, because when used for object reference, Final makes the reference constant, and once the reference is initialized to an object, it can no longer be pointed to another object. However, the object itself can be modified, and Java does not provide a way to make any object constant (but you can write your own class to achieve a constant effect on the object), the same restriction applies to the array, it is also an object.

Can using the final method really improve program efficiency?
Once a method is set to final, the compiler can place all calls to that method into an "embedded" call. As soon as the compiler discovers a final method call, it ignores (according to its own judgment) the general code insertion method taken to execute the method invocation mechanism (the argument is pressed into the stack; jumps to the method code and executes it, jumps back, clears the stack argument, and finally processes the return value). Instead, it replaces the method call with a copy of the actual code within the method body. Doing so avoids the overhead of the method invocation. Of course, if the method size is too large, then the program will become more and more swollen, may not be affected by the embedded code of any performance improvement. Because any ascension is offset by the time spent inside the method.

Virtual machines, especially hotspot technologies, can automatically detect these situations and, rather "wisely", decide whether or not to embed a final method. However, it is best not to fully believe that the compiler can make all the judgments correctly. Typically, you should consider setting a method to final only if the code for the method is very small, or if you want to explicitly prohibit the method from being overwritten.

All private methods within a class are automatically final. Since we cannot access a private method, it will never be overwritten by other methods (if forced to do so, the compiler will give an error). You can add a final indicator to a private method, but you cannot provide any additional meaning to that method.

Remember that you should consider setting a method to final only if the code amount of the method is very small, or if you want to explicitly prohibit the method from being overwritten.

9.

Resources:

The idea of Java programming

Http://www.cnblogs.com/lanxuezaipiao/p/4153070.html

Java key points of knowledge

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.