Java Programming thought Seventh chapter

Source: Internet
Author: User
Tags export class soap

7.1 combination Syntax

1) Combining object references into new classes

2) Each non-basic type of object has a ToString () method, and the method is called when the compiler needs a string and you have only one object.

3) There are four ways to initialize an object reference in a class:

1. Initialization where the object is defined, meaning that it is always initialized before the constructor is called

2. In the constructor of the class

3. Just before using these objects, this is called lazy initialization, which can reduce the additional burden

4. Use instance initialization

classSoap {PrivateString S; Soap () {print ("Soap ()"); //2. Initializing in the constructor of a classs = "Constructed"; }   PublicString toString () {returns;}}  Public classBath {PrivateString//1. Initialize the object where it is defined:S1 = "Happy", S2= "Happy", S3, S4; PrivateSoap Castille; Private inti; Private floattoy;  PublicBath () {print ("Inside Bath ()"); //2. Initialize in the constructor of the class:S3 = "Joy"; Toy= 3.14f; Castille=NewSoap (); }   //4. Initialization of the instance:{i = 47; }  PublicString toString () {if(S4 = =NULL)//3. Lazy initialization (Delayed initialization):S4 = "Joy"; return"S1 =" + S1 + "\ n" + "s2 =" + s2 + "\ n" + "S3 =" + s3 + "\ n" + "S4 =" + s4 + "\ n" + "i =" + i + " \ n "+" toy = "+ toy +" \ n "+" Castille = "+Castille; }    Public Static voidMain (string[] args) {Bath b=NewBath ();  Print (b); }} /*output:inside Bath () Soap () S1 = Happys2 = Happys3 = Joys4 = Joyi = 47toy = 3.14castille = Constructed

7.2 Inheritance Syntax

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

2) Inheritance keyword extends : Inheritance automatically gets all the domains (what are domains) and methods in the base class.

3) Calling the main function of another class is the same as calling a normal static function of another class, that is 类名.main(args); , args can be a parameter from the command line that the keynote class uses, or it can be any other string array.

4) You can create a main method for each class. This technique, which sets a main method in each class, makes unit tests for each class simple and easy. And after you complete the unit test, you don't have to delete main (), which you can leave for the next test.

5) Even if a class has only package access, its public main () is still accessible. (not confirmed yet?) )

6) In order to inherit, the general rule is that all data members are designated as Private, all methods are specified aspublic (the protected method can also be accessed with the help of an export class, as mentioned later).

7) Java uses the Super keyword to represent the superclass (parent class). An expression super.fun(); can call a function in the parent class (here is the call Function Fun ()).

7.2.1 Initializing a base class Note:Base class = parent class; Export class = subclass.
1) When you create aexporting objects of a class, the objecta child object that contains a base class, the child object is wrapped inside the exported class object.
2) Initialization of the base class sub-object: Call the base class constructor in the constructor to perform the initialization.                                       The definition is initialized, the instance is initialized, and so on before the base class constructor is executed. ※java willautomatically in the constructor of the exported classIninserting a call to the base class constructor .

Example code:
classArt {PrivateString art = "Test art.\n"; PrivateString ArtS; {ArtS= "ART"; } Art () {print ("Art Constructor" +art+ArtS); }}classDrawingextendsArt {PrivateString draw = "Test drawing.\n"; PrivateString draws; {Draws= "DRAW"; } Drawing () {print ("Drawing Constructor" +draw+draws); }} Public classCartoonextendsDrawing { PublicCartoon () {print ("Cartoon constructor"); }   Public Static voidMain (string[] args) {Cartoon x=NewCartoon (); }} /*Output:art Constructor Test Art. Artdrawing constructor Test Drawing. Drawcartoon Constructor

As you can see, the build process is diffused from the base class "outward", so the base class is initialized before the export class constructor can access it. Of course, the default constructor also dispatches the constructor of the base class layer by level.

7.2.2 with parametric constructors

The compiler can call the default constructor automatically because they do not have any parameters.

However, if there is no default base class constructor, or if you want to invoke a base class constructor with parameters, you must use the keyword Super to write the statement that calls the base class constructor, with the appropriate argument list.

If the base class does not have a default constructor (no parameter constructor), the export class does not explicitly call the base class's parameter constructor , and the compiler will error .

7.3 Agents

The agent is the third type of reuse code, and Java does not provide direct support for it. It is the middle doctrine between inheritance and composition:

    • First, we need to place a member object in the class to be constructed ( just like a combination );
    • Second, we need to expose all methods of the member object ( like inheritance ) or a subset of all methods of the member object in the new class.

Example code:

 Public classSpaceshipcontrols {voidUpintVelocity) {}  voidDownintVelocity) {}  voidLeftintVelocity) {}  voidRightintVelocity) {}  voidForwardintVelocity) {}  voidBackintVelocity) {}  voidTurboboost () {}} Public classspaceshipdelegation {PrivateString name; PrivateSpaceshipcontrols controls =NewSpaceshipcontrols ();  Publicspaceshipdelegation (String name) { This. Name =name; }  //Delegated methods:   Public voidBackintVelocity)  {controls.back (velocity); }   Public voidDownintVelocity)  {Controls.down (velocity); }   Public voidForwardintVelocity)  {Controls.forward (velocity); }   Public voidLeftintVelocity)  {controls.left (velocity); }   Public voidRightintVelocity)  {controls.right (velocity); }   Public voidTurboboost () {controls.turboboost (); }   Public voidUpintVelocity)  {controls.up (velocity); }   Public Static voidMain (string[] args) {spaceshipdelegation Protector=NewSpaceshipdelegation ("Nsea Protector"); Protector.forward (100); }}

Inverse code:

 Public classSpaceshipextendsspaceshipcontrols{PrivateString name;  Publicspaceship (String name) { This. Name =name; } @Override PublicString toString () {returnname; }     Public Static voidMain (string[] args) {spaceship ship=NewSpaceship ("Nsea Protector"); Ship.foward (100); }}

Spaceship is not a true spacesbipcontrols type, even if you can "tell" spaceship forward movement (forward ()). More accurately, spaceship contains Spaceshipcontrols, while all spaceshipcontrols methods are exposed in spaceship (not knowing where to expose them). The above example can be solved.

7.4 Combining and inheriting using combinations

You can create more complex classes by using both composition and inheritance, with the necessary constructor initialization.

7.4.1 ensure proper cleanup
Try {  //......} finally {  x.cleanup ();}

The finally clause in the preceding code indicates that "no matter what happens, be sure to call Cleanup () for x." ”
In the Cleanup method (Dispose ()), you must be aware of the order in which the base class cleanup methods and member object cleanup methods are called in case a child object is dependent on another child object.

If one sub-object is to be based on another. In general, you should take the same form as the C + + compiler does with its "sabotage": first complete all the special work related to the class (which may require that the underlying class elements remain visible), and then call the underlying class cleanup method.
    • In general, it takes the form that the C + + compiler imposes on its destructor: first, all of the specific cleanup work for the class is performed in the same order as the build order (usually this requires that the base class element still survives), and then the cleanup method of the base class is called.
    • Note: You cannot rely on the garbage collector to do anything other than memory. If you need to clean up, you might want to write your own cleanup method, but do not use Finalize ().
7.4.2 Name Masking
    • If the base class of Java has a method name that has been overloaded multiple times, redefining the method name in the export class does not mask any one version in the base class (this is different from C + +). Therefore, the overloading mechanism works correctly, whether the method is defined in the layer or in its base class.

    • If you just want to overwrite a method, but fear not to pay attention to overloading the method (rather than overriding the method), you can choose to add @Override annotations (Java SE5 new).

    • Before a method adds @Override annotations, the method can only overwrite a method of the parent class, and if you do not pay attention to the overloaded, the compiler will error. This way @Override , annotations can prevent you from accidentally overloading when you don't want to reload them.

7.8 Final keyword 7.8.1 data

The declaration data is a constant, either a compile-time or a constant that cannot be changed after the runtime is initialized.

    • For basic types, final causes the values to be unchanged;
    • For reference types (including arrays), Final makes the reference unchanged and cannot reference other objects, but the referenced object itself can be modified.
Final int x = 1= 2;  // cannot assign value to final variable ' x ' Final New  = 1;

Blank final: Refers to a field declared final but not given an initial value. However, blank final must be assigned a value in the constructor with an expression . Examples are as follows:

classpoppet {Private inti; Poppet (intII) {i =II;}} Public classblankfinal {Private Final inti = 0;//Initialized Final  Private Final intJ//Blank Final  Private FinalPoppet p;//Blank Final Reference//Blank Finals must be initialized in the constructor:   Publicblankfinal () {J= 1;//Initialize blank Finalp =NewPoppet (1);//Initialize blank Final reference  }   PublicBlankfinal (intx) {J= x;//Initialize blank Finalp =NewPoppet (x);//Initialize blank Final reference  }   Public Static voidMain (string[] args) {Newblankfinal (); NewBlankfinal (47); }}

In summary, you must assign a value to the fianl in the field outside the definition or in each constructor with an expression.

7.8.2 method

There are two reasons to use the final method:

    • Lock the method to prevent any inherited classes from modifying its meaning. This is a design consideration: Make sure that the method behavior remains the same in the inheriting class and will not be overwritten.
    • Efficiency: Similar to the C + + inline mechanism, the early VM needs are not needed now, so it is now not necessary to use the final method for optimization.
      In summary, you make the method final only if you want to explicitly block the method from being overwritten.

Declaring a method cannot be overridden by a quilt class.

The private method is implicitly specified as final, and if the method defined in the subclass is the same as a private method signature in the base class, the method of the subclass is overloaded instead of overriding the base class method.

The final method is similar to the private method, except that private can only be accessed within the class, not accessible outside the class, the final method can be accessed outside the class, but cannot be overridden, can use the functionality of the method but cannot change its functionality

7.8.3 class

Final is placed before the definition of the class to indicate that the class is not allowed to be inherited . This is done for the following reasons:

    • For some reason, you never have to make any changes to the design of the class;
    • For security reasons, you don't want it to have subclasses.

Java Programming thought Seventh chapter

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.