[Thinking in Java] Chapter 7th-Reuse Class

Source: Internet
Author: User

7.1 Combination Syntax 7.2 Inheritance syntax 7.3 Proxy 7.4 overloads and overwrite 7.5 initialization and class loading
Catalogue


7.1 Combination Syntax

The combination is to put the object in a new class, to be a member of a new class, such as

class A {} class B {    private  String value1, value2, value3;     Private New A ();     Private int integer;     Private Double D;}

As shown above, the Class A object becomes as one of Class B, in addition, Class B has a class String3 object, and the basic data type integer and D.

If you want to initialize a class, you can do it in 4 locations in your code.

1. Where the object is defined;

2. In the constructor of the class;

3. Use instance initialization, which is the initialization block

4. This is also known as lazy initialization before using this object, which can reduce the additional burden.

classa{}classB {//1. Where the object is defined    PrivateString name =NewString ("Xiaoming"); PrivateString sex;//not initialized    Private intId//not initialized    PrivateA;//not initialized         {//4. Using instance initializationID = 13; }      PublicB () {//2. Initializing in the constructorA =NewA (); }     Public voidf () {//4. Initializing when using this object        if(Sex = =NULL) Sex= "Boy"; System.out.println ("I am A" +sex); }}

7.2 Inheritance Syntax

When a class is created, it is always inherited, so unless explicitly stated to inherit from another class, it is always implicitly inherited from the Java standard root class object.

classA {Private intA; Private Doubleb; PrivateString name;  Public voidF1 () {} Public voidF2 () {}}classBextendsA {Private intC;  Public voidF3 () {}}

As shown in the code above, using the keyword extends, Class B inherits Class A and obtains all the properties and methods of the parent class, including the private property of the parent class

classPerson { PublicString toString () {return"I am a person"; }}classFatherextendsPerson {PrivateString name = "Xiaoming";  PublicFather (String name) { This. Name =name; }         PublicString toString () {return"I am a Father"; }         PublicString GetName () {returnname; }}classSonextendsFather { PublicSon (String name) {Super(name); }         PublicString toString () {return"I am a Son"; }} Public classPersontest { Public Static voidMain (string[] args) {Father Father=NewFather ("Small Day"); Son son=NewSon ("Xiao Qiang"); Father.say ("My name is" +father.getname ()); Son.say ("I am" +son.getname ()); }}

As shown in the code above, class father defines the property name of the private adornment, is inherited by the class son and initialized in the constructor, and the class father defines the accessor getname (), because it is decorated with public, so the object of class son can be used directly We can also notice that the class person defines the public method, ToString (), in fact the root class object also defines ToString (), but the ToString () of the class person is overloaded because the method signature is not the same, The class father also defines the ToString () of the same method signature, which is the ToString () of the overridden class person, and the ToString () of the class son overrides the ToString () of the class father.

Notice that the constructor of class son is super (name); If you comment out this sentence or change to super (), the compiler can only make an error because the inheritance mechanism requires the parent class to be initialized:

In fact, inheritance does not just replicate the interface of the parent class, when an object of a subclass is created, the object contains a child object of the parent class, which is the same as the object that you created directly from the parent class, except that the latter comes from outside and the child objects of the parent class are wrapped inside the subclass object. Proper initialization of parent child objects is also critical, and there is only one way to do this is to call the constructor of the parent class in the early constructor to perform the initialization.

class Art {    art () {System.out.print ("Art Builder");}} class extends Art {    Drawing () {System.out.print ("Drawing Builder");}} class extends Drawing {    Cartoon () {System.out.print ("Cartoon constructor");}}

As shown in the code above, when initializing cartoon, the parent class drawing is found, so the compiler defaults to adding a super () to the first sentence of the constructor, initializes the parent class drawing, and discovers that there is a parent art, so the default is to add a super () to the first sentence of the constructor. , and then initialize the parent art, for the root class object is not said, so the output result is

Art Builder drawing constructor cartoon constructor

Can the first row of the constructor be super (the super that initializes the parent class must be the first row) with parameters? Of course, like the example above, super (name) is a parameter in the constructor of class son, but if you remove the parameter name or simply do not write it, the compiler complains that it cannot be initialized because the parent class father does not exist without the argument constructor. What if this is the case?

classa {a () {System.out.println ("A without reference"); }}classBextendsA {B () {System.out.println ("B No Reference"); } B (inta) { This(); System.out.println ("B has the ginseng"); }}classCextendsB {C () {Super(1); System.out.println ("C without reference"); }} Public classInheritance { Public Static voidMain (string[] args) {NewC (); }}

Because this construction method chain starts from the initialization object and ends at the root class object. So when the This () is executed, the program jumps to the B () constructor, but at this point the entire construction method chain has already been completed, naturally not super to the parent class A, so the program output is

A no parameter b no parameter B has parameter c no parameter

7.3 Agents

The relationship between classes is composed, inherited, and a third relationship becomes a proxy, and Java does not provide direct support for it, which is the middle of the combination and inheritance.

Because we put a member object in the class we want to construct (like a combination), but at the same time we expose all the methods of this member object (like inheritance) in the new class, the agent solves the challenge

class A {    f1 (int  i) {}    f2 (int  i) {}}}class  B    { C11>new  A ();        F1 (int  i) {        a.f1 (i);    }        F2 (int  i) {        a.f2 (i);    }}

As shown in the code above, at design time, we want to use the F1 and F2 methods of B instead of using A's F1 and F2 methods, for example, we want a car to move forward rather than let the car's control engine drive forward.

7.4 Overloading and overwriting

Overloading is the same method name, and the parameter list is different, allowing the return value type is different, where the parameter list is different from the number and type of parameters;

Overrides are subclasses that override a method of a parent class, the method name of a method of a subclass, the return value type, and the argument list must be identical to a method of the parent class.

1 classA {2     intMethodinti) {3         returni;4     }5 }6 7  Public classBextendsA {8      Public intMethodinti) {9         return++i;Ten     } One      A     DoubleMethodDoubled) { -         returnD; -     } the      -     DoubleMethodintADoubleb) { -         returnA +b; -     } +      -      Public Static voidMain (string[] args) { +B C =NewB (); ASystem.out.println (C.method (1)); atSystem.out.println (C.method (5.6));
System.out.println (C.method (5, 5.5)); - } -}

Note that if the modifier for the 8th line of code is changed to private, the compiler complains that the modifier's visibility is lower than that of the parent class, so it must be guaranteed that the modifiers are not less visible than the parent class, and that the 12th to 14th line is a method that overloads the parent class, where the return value type can be different , the 16th to 18th line is also overloaded with the method, where the number of argument lists is different

7.5 Initialization and loading of classes

The compiled code for each class exists in its own standalone file, although a Java file can have more than one class. The file is loaded only if you need to use the program code. In general, the code for a class is loaded only when it is first used. This usually refers to the load that occurs when the first object of the class is created, but also when the static domain or static method is accessed.

The first use is where static initialization occurs. All static objects and static code snippets are initialized in sequence in the program as they are loaded. Of course, what is defined as static will only be initialized once.

Here is an example of the idea of Java programming

1 Import Staticjava.lang.system.*;2 3 classInsect {4     Private inti = 9;5     protected intJ;6 insect () {7Out.println ("i =" + i + ", j =" +j);8j = 39;9     }Ten      One     Private Static intX1 = APrintinit ("Static insect.x1 initialized"); -      -     Static intPrintinit (String s) { the Out.println (s); -         return47; -     } - } +  -  Public classBeetleextendsInsect { +     Private intK = Printinit ("beetle.k initialized"); A      PublicBeetle () { atOut.println ("k =" +k); -Out.println ("j =" +j); -     } -      -     Private Static intx2 = -Printinit ("Static beetle.x2 initialized"); in      -      Public Static voidMain (string[] args) { toOut.println ("Beetle constructor"); +Beetle B =NewBeetle (); -     } the}

When running Java on Beetle, the first thing that happens is trying to access Beetle.main () (a static method), so the loader starts and finds out the compiled code for the Beetle class (in a file called Beetle.class). As you load it, the compiler notices that it has a parent class (known by the keyword extends), so it continues to load, regardless of whether you intend to create an object of that parent class, which happens.

If the parent class has its own parent class, then the second parent class is loaded, and so on. Next, static initialization in the root parent class (in this case, insect) is executed, followed by the next subclass, and so on.

So far, the necessary classes have been loaded and the objects can be created. First, all the basic types in the object are set to the default values, and the object references are set to NULL. The constructor of the parent class is then called. In this case, it is automatically called. However, you can also use super to specify a call to the parent class constructor (as in the first step in the constructor of Beetle ()). The parent class constructor, like the constructor of a subclass, undergoes the same procedure in the same order. After the parent class constructor is complete, the instance variables are initialized in their order. The remainder of the last constructor is executed.

As this example, when trying to access Beetle.main (), the first attempt to load the Beetle class, but found Beetle's parent class insect, so first load Insect,insect first static statement is the 11th row, The 11th line then calls the 14th row of Printinit (string s), prints S and returns 47, so x1=47, and then loads Beetle, the first static statement is line 27th, and the 27th row calls the parent class Printinit (string s), Print S and return 47, so x2=47, so that all classes have been loaded, go back to Beetle.main (), execute line 31st of the statement, and then execute line 32nd, create the Beetle object, and then try to execute the 22nd row of the constructor, but found that there is a parent class insect, Thus, the parent class is initialized first, the program jumps to line 6th, the constructor of the parent class is called, the parent class is initialized, the subclass is initialized, and so on, the Beetle object is created successfully.

[Thinking in Java] Chapter 7th-Reuse Class

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.