JAVA knowledge summary (three): inheritance and access modifiers

Today there are some riding time, the legacy of the three major characteristics of the object-oriented programming in the last arrears inheritance and polymorphism to briefly explain. This part is very important and needs careful consideration.

inherit

Inheritance: it is a relationship between class and class, to create a new class by using the existing class as a basis. Wherein the existing class is called the parent class (or base class); establishing a new class is called the child class (or derived class). The simplest is to subclass inherits the properties and non-private methods of the parent class.

It should be noted that the newly defined class can choose to continue to use the functionality of the parent class of its own or to add new data or new features, but can not selectively inherit the parent class . (Either inherit all (the premise of non-private) or not inherited)

As long as it satisfies the relationship of "A is a B" form of inheritance, inheritance code is achieved by the extends keyword.

Special Note: only inherit a parent class (that is, single inheritance) in java, and subclasses can access non-private members of the superclass. This is not the same and Python, Python may inherit flexible.

After we know subclass inherits the parent class, you can access private members of the superclass; but private members of the parent class, subclass or can not be accessed directly. If we want to access it? It may be accomplished indirectly via the public methods of the parent class exposure.

Not have access to the parent class object subclass specific method or property, while the parent can not access the unique subclass members (even the public member)

Overload

Method overloading must meet the following conditions:

  1. The same class ;;
  2. The same method name, a list of different parameters (parameter order, number, type);
  3. Method returns a value, any access modifier;
  4. Regardless of the method of parameter names.
public void printinfo() {
    System.out.println("方法重载1");
};

public void printinfo(String name) {

    System.out.println("方法重载2");
};

public String printinfo(String name, int age) {
    return "方法重载3";
};

public String printinfo(String age, String name) {
    return "方法重载4";
};

public String printinfo(int age, String name) {
    return "方法重载5";
};

 // 与方法的参数名无关,加上下面的代码会和上面的 printinfo(int age, String name)造成重复而报错:
public String printinfo(int size, String name) {
    return "方法重载5";
};

Rewrite

The method of rewriting must also meet the following criteria:
1, the subclass inherits satisfy relations;
2, the name of the same method, the same (parameter order, number, type) parameter list;
3, the return value of the method is the same subclass or type (but not of type Object, it can be backward compatible, up is not possible);
4, access modifier is greater than or equal to limit the scope inherited methods.
(A large two small, to limit the scope of the access modifiers subclass parent or greater; return type and exceptions require less parent subclass)
Note: In a subclass can be defined in the parent class of the same name property, but that does not mean that property can be rewritten.

Access modifier

In Java which contains a total of four kinds of access modifiers, namely:
1, Private: private;
2, default;
3, protected: protected;
4, public: public.

Wherein, Private : Access is permitted only in the scope of this class, the class is not allowed to leave the current access;

Default : Allows the current class, with buns class / non-child class can be called cross buns class / non-child classes are not allowed;

protected : it allows the current class, subclass in the same package / non-child class can call the class as well as cross buns. Cross package of non-child class calls are not allowed.

public : allows access anywhere.

Accordance with the previous order, from top to bottom, increasing access range; bottom-up, limiting the growing ability:

(Including the same packet type with non-child classes and buns; buns with class comprises subclasses cross buns and the like)

Affect the access modifier of overridden methods

When subclass overrides the parent class method access modifier is allowed to change, it is required: the access range subclass must be greater than equal to the access range of the parent class. This means that if the parent class access modifier is public, then the subclass access modifier must be public, other similar.

Inherited initialization sequence

After the initialization sequence of inheritance are as follows:

Parent class static member -> subclass static members -> parent object constructor -> Constructor class object
constructor> parent class - (parent class static member -> subclass static members -> parent object constructor - > constructor class objects -> constructor subclass)

One problem: access modifiers influence the members of the loading sequence takes precedence over the static member static code block execution??

Access modifier does not affect members of the loading sequence, with the position of writing about. If the static block of code written in front of the static variable, it runs the static code block.

super keyword

If a subclass inherits and overrides the parent class, then we usually call that a subclass method rewritten. If you need to call the parent class method, we can use super.方法to achieve this objective.

Of course, it can also be used super.属性to achieve the purpose of access to non-proprietary property of the parent class.

Although access modifier constructor of the parent class is public, but it can not be inherited by subclasses and overridden.

Although it is not two, but its presence is necessary, since the subclass is instantiated object constructor depends on the parent class object (the default, no reference or constructor argument).

If a subclass constructor calls the argument that they have, and the parent class defines the parameters and the constructor has no parameters, the program is still calling the parent class constructor with no arguments. In other words, our not explicitly noted in the sub-class constructor, the default constructor without parameter to call the parent class, so no-argument constructor of the parent class is very important, be sure to write, otherwise it will affect the subclass instantiate an object.

If the subclass constructors neither explicitly labeled and not the parent class constructor with no arguments, a compilation error is raised.

We can use super(参数)this form to call the parent class constructor allows other methods to be accessed, but this time super () must be placed in the first row subclass valid code constructor (the constructor must subclass (all else fails) the first line (other okay)).

That parent class is instantiated when the default constructor calls the no-argument (in this case you do not define no-argument constructor is possible), but if the subclass does not show signs of the time the object is instantiated (that is, the default constructor will call the superclass no-argument), but this time the parent is actually a no-argument constructor does not exist, it will trigger a compilation error.

Comparison of this and super

this: this class object reference:
1, the current class method access members;
2, properties of the current access class members;
3, access to the current class constructor;
4, can not be used in a static method;
****
Super: parent class object reference:
1, a member of the parent class method access;
2, a member of the parent class attribute access;
3, access to the parent class constructor;
4, can not be used in a static method;
****
Note: call when the constructor, this can not exist simultaneously and super (both of which are required in front of said first row).

Object class

Object class is the parent of all classes, and this in fact almost in Python, which is all the Python classes inherit from this base class object. This point of view direct API: javase8api

A class does not explicitly identify the keywords to use extends inheritance, by default inherit the Object class (including arrays).

Class Object is the root of the class hierarchy.
Every class has Object as a superclass. 
All objects, including arrays, implement the methods of this class.

Object class stored in the java.lang package, this package will by default be loaded directly to us.

equals Usage

If the subclass does not rewrite the equals method of Object class, then the comparison is whether the two references point to the same address; and String class overrides the equals method of the Object class, so the comparison is a value of the string are equal. (Implication, subclasses can override the equals method form, change the contents of the comparison)

So we can not say that two objects equals the value of the comparison, or reference to address, but we can say that "==" comparison but it must be referenced addresses of the two objects.

toString usage

api tell us, toString finally returns to this to :( package name. Class name @ memory hash code)

 getClass().getName() + '@' + Integer.toHexString(hashCode())

Similarly, if the subclass method toString Object class does not override, the output hash code is printed in memory; and class String toString method rewrote Object class, and the printed output their true values. (Implication, a subclass can override toString method form, change the contents of the output)

It is also noted that is the output 对象and 对象.toStringthe effect is the same as when the direct output target is actually called the object .toString method.

Final Keyword

When we do not want certain class is inherited, some method is overridden or some data is modified, you can use the final keyword for this purpose.

If a class is modified final, it indicates that the class can not be inherited, the class is not a subclass, public final class / final public class can, as long as it can be placed in front of the class;

If a method is final modification, it indicates that the method can not be overridden, but does not affect the subclass to inherit call it (final constructor can not be modified).

If a local variable is final modification, then we can not immediately be declared at the same time assignment, but must be assigned before use, once the assignment can not be modified;

(Local variable in the scope of the method, starting from the line to the end where the braces; the scope of the class member variable depends on its front access modifier);

If a member variable is final modification, it was immediately assigned the same time we also need not be declared, but must be assigned before use, and can only be assigned in the constructor or class code block (block structure), once the assignment on It can not be modified; attribute that is assigned class members can have three ways: 1. the definition of direct initialization; 2. constructor; 3. configured block (class code block).

Note: When you have more than one constructor, final keyword modified if the member variables selected for assignment inside the constructor, you need to assign a value inside all constructors, but different construction methods can be assigned different values

Final impact on the type of data

We know that java data types are divided into basic data types (byte, short, int, long, float, double, char, boolean) and reference data types (array, String, interface, custom classes ...)

The basic data types that can be assigned directly, but reference types need to instantiate an object of the class before they can be assigned to its target (String this is rather special, two forms are possible)

We know the basic types of data stored in memory is the data itself, and the type of reference data stored in memory is the object reference address.

The following example tells us that the modified final, must not modify its reference address, but the property is possible:

final Test test=new Test("hello");  
//      test=new Test ();
        Test.key="world";

It boils down to this: the basic data types of variables that once initial value can not be modified; and a reference type variable only after the initialization can not point to another object, but the content of the object is variable.

Thus with static final be used for modification methods and variables. It is typically used to modify the configuration information (such as information needs to be loaded only once, and need not be modified later). The implication, using the final modification can improve performance, but reduces scalability.

Common code block, code block type, block structure, the difference between the static code block

Code block are a pair of braces {} are enclosed content.

Common code block is a pair of braces {} are enclosed content, exists only in the class methods;

Class code blocks and code block is constructed a thing, is directly defined in the class, not previously be modified static. Code block is configured to be called when the object is created each time will be called to create an object, and the execution order of the code block structure in preference class constructor.

Static preceding code block has modified static keyword that does not exist in any in vivo method, you can not directly access the instance variables and instance methods, by way of example need to access the object class.

Usually we new object, JVM to go through such an initialization sequence: a static block parent class> sub-class static blocks> parent attribute> parent class constructor> child property> sub-class constructor, this series will consume a lot of work memory and cpu.

Specific studies can see here: Explanation of four kinds of code block java .

java annotations in

JDK1.5 annotation is a characteristic release introduced, it can declare that these elements will be described in the package, classes, properties, methods, local variables, parameters, etc. The method of the foregoing, the role annotation.

Classified in accordance with the operating mechanism

Notes in accordance with the operating mechanism to be divided, can be divided into three parts: source notes, compile-time annotations, notes runtime.

Source Note: only present in the source .java files, compiled into bytecode .class file does not exist;

Annotations compilation: .java files are present in the source code and byte .class files;

Notes runtime: also play a role in the operational phase, and even affect the operation of the logic of notes. (Spring frame such annotations @Autowired dependency injection, it is achieved in the process of running the program will automatically load into the incoming external message, which is a kind of operation can affect the operation of the program logic of the annotation.)

According to sources of points

Notes according to the source to be divided, can be divided into three parts: the JDK annotations, third-party annotation, custom annotations.

There is also a meta-annotation, it is the annotated notes.

Die, read, read the words and ultra-fast word of 4000, the last object-oriented features: polymorphism, I did not say, next time, the movement today was rolled away. . . Thank you for reading tours.

Guess you like

Origin www.cnblogs.com/envythink/p/11871385.html