A little bit of Java (2)

Source: Internet
Author: User

  • 1 Object-oriented three principles the basic unit of encapsulation encapsulation is class, the class is an abstract logical structure, and the object of the class is a real physical entity; The purpose of the class is to encapsulate complexity, and there is a hidden implementation complexity mechanism within the class; Encapsulation (encapsulation) Two benefits: Modular: Can be independent of the source code of other objects to write and maintain, you can easily transfer objects in the system; Hide information: Other objects can communicate through one of the public interfaces of this object without affecting other objects;  inheritance Inheritance is the process by which an object obtains the properties of another object, which is the possibility that an object becomes a specific instance of a more general class, avoids duplication of code, polymorphism  (overloaded overload, the same method name, different number of parameters, different types of parameters, The type of return differs and overrides override); polymorphism is "an interface, a variety of methods", can be a set of related actions to design a common interface, in fact, the overload of the function of the class is a multi-state embodiment; 4 the idea of introducing abstract programming; Class encapsulation is an abstract idea.
  • In addition to the static method and the final method in Java (the private method is essentially the final method, because it cannot be accessed by a quilt), all other methods are dynamically bound , which means that normally we don't have to decide whether we should bind dynamically- It will happen automatically.
    • 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:
      ClassStaticsuper{PublicStaticStringStaticget(){Return"Base Staticget ()";}PublicStringDynamicget(){Return"Base Dynamicget ()";}}ClassStaticsubExtendsStaticsuper{PublicStaticStringStaticget(){Return"Derived Staticget ()";}PublicStringDynamicget(){Return"Derived Dynamicget ()";}}PublicClassStaticpolymorphism{PublicStaticvoid main(String[] args) { staticsuper sup = new staticsub  (); System.  Out.  println(sup.  Staticget()); System.  Out.  println(sup.  Dynamicget()); }}< /c17> 

      Output:

      Base Staticget ()
      Derived Dynamicget ()

  • constructors are not polymorphic, they are actually static methods, except that the static declaration is implicit. Therefore, the constructor cannot be override.

  • 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.

    ClassGlyph{voidDraw(){System.Out.println("Glyph.draw ()");}Glyph(){System.Out.println("Glyph () before Draw ()");Draw();System.Out.println("Glyph () after draw ()");}}ClassRoundglyphExtendsGlyph{PrivateIntRadius=1;Roundglyph(IntR){Radius=R;System.Out.println("Roundglyph.roundglyph (). Radius = "+Radius);}voidDraw () {system. Out. (" Roundglyph.draw (). Radius = "+ radius); }}public class  Polyconstructors {public static void main (string[] args) {new roundglyph (5}             /span>                


    Output:

    Glyph () before draw ()
    Roundglyph.draw (). Radius = 0
    Glyph () after draw ()
    Roundglyph.roundglyph (). RADIUS = 5

Why is this output? This requires a clear understanding of the order in which constructors are called in Java :

(1) Initialize the storage space allocated to the object into binary 0 before anything else occurs;
(2) Call the base class constructor. Recursively from the root, since polymorphism calls the draw () method after the subclass overrides (to be called before calling the Roundglyph constructor), we will find that the radius value is 0 at this point because of step 1.
(3) The initialization method of invoking members in the Order of Declaration;
(4) The constructor of the subclass is called last.

    • Only non-private methods can be overwritten, but you also need to pay close attention to the behavior of the private method, while the compiler does not error, but it does not follow what we expect, that is, overriding the private method is a new method for a subclass rather than an overloaded method. Therefore, in a subclass, the new method name is best not to take the same name as the private method of the base class (though it doesn't matter, but is easy to misunderstand, to be able to override 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. attributes with the same name as the parent and child classes will be allocated different storage spaces , as follows:

      Direct field access is determined at compile time.ClassSuper{PublicIntField=0;PublicIntGetField(){ReturnField;}}ClassSubExtendsSuper{PublicIntField=1;PublicIntGetField(){ReturnField;}PublicIntGetsuperfield(){ReturnSuper.Field;}}PublicClassFieldaccess{PublicStaticvoidMain(String[]Args){SuperSup=NewSub();System.Out.println("sup.filed ="+Sup.Field+", Sup.getfield () ="+Sup.getfield ()); sub sub = new sub (); system.. ( "sub.filed =" + sub.field + + subgetfield () + + sub. Getsuperfield}             /span>                


      Output:

      sup.filed = 0, Sup.getfield () = 1
      sub.filed = 1, Sub.getfield () = 1, Sub.getsuperfield () = 0

      The Sub subclass actually contains two fields called field, whereas the default domain generated by referencing field in sub is not a super version of the Field field, so in order to get Super.field, you must explicitly indicate Super.field.

A little bit of Java (2)

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.