Java Programming Idea (iv)--reuse class

Source: Internet
Author: User
Tags visibility

See Old Luo Luo Shenyang's special visit, involuntarily admire, very young, I thought before and yonghao a level of age. It was one of Daniel's first high school programmers who had seen it. I found that Lao Luo is also a step by step Person.

Don't say what is hard to do, can't do it. You didn't try it at All. Not to Insist.


If you can ' t fly so run,if you can ' t run then walk, if you can ' t walk then crawl,but

Whatever you do,you has to keep moving forward--martin Luther King.


The title of the reuse class is very difficult to understand just beginning. The back of the book to read the original English. In fact the title is reusing classes, another use of the class, in fact, reuse is the "use of ready-made things" means. In fact, the two methods of implementation are often heard in java--combination and Inheritance.


(1) Combination

The role of Has-a.

public class TV {   show show;   Public String toString () {     return ' showgirl ';   }} Class show{}

To mention the ToString method, when you need a string and you are an object, the compiler invokes the Object's ToString Method.

There is a show on tv, and Today's show is not initialized. Is null, the method of show cannot be called.


A combination of powerful, object-oriented look, If you are building a car class, then you can use the combination of glass,light,engine and so on the car of these parts together.


(2) inheritance

Is-a

Package Com.myown.iaiti;public class Father {public     int i;     void Get () {System.out.println ("father");        }}package son;import com.myown.iaiti.*;p ublic class Son extends Father{Father f = new Father ();        Int J = f.i;        Son son = new son ();    Son.get ();        } public void get () {super.get (); System.out.println ("son");}    }

Here is a question about the access permissions of the package, if there is no time to add public. The default is In-package membership Access. Access to different packages, that is, the father members of son visiting the Get method is not visible. And the public word is visible, so I access to Ask.


The private part is a part that cannot inherit, belongs to the parent class, and is Public. Will inherit, need to change the method, can be Rewritten. The attributes to be added can be added separately.


And the inherited Method. Assuming the original Father public method has not been added after the public, there will be cannot reduce the visibility of the inherited method from Father, That is, you cannot reduce the visibility of inherited methods in the parent class.

Super refers to the parent class, which is father.


Another point is that in fact all classes in Java implicitly inherit the object class. Object is a parent class, other classes are subclasses

Foreigners like to speak as a base class. Subclasses are also called export classes or derived Classes.


(3) Agent

The design pattern has a more difficult-to-understand-agent mode, the author is very interesting. Proxies are the middle of the combination and inheritance.

Package Son;class father{public    void get () {        System.out.println ("Father");}    } public class Son extends father{public    static void main (string[] Args) {        Father f = new Father ();        F.get ();    }} Class fatherproxy{    private Father f = new Father ();    public void Get () {        f.get ();    }}

like directly father as a member, then the Father method is exposed to this class, then we can use Fatherproxy proxy class. I'm Customizing how the Get method is taken, and I know it's a Get method that calls Father. But the person who uses my agent does not know, I just tell him that you need to use the proxy get method can Be. Encapsulation is the embodiment of The. The above is just a simple example of random knocking.


(4) overriding and overloading

Class father{public    void get (String s) {        System.out.println ("Father");    }        public void Get (boolean b) {        System.out.println ("boolean");}    } public class Son extends father{    @Override public    void get (String s) {        System.out.println ("Father");    }       //@Override//there will be an error message because the parent class does not have the method, not the override public    void get (int i) {        System.out.println ("sonint");    }        public static void main (string[] Args) {        son s = new Son ();        S.get ("d");        S.get (false);        S.get (1);}    }

overrides are another way of overwriting a parent class, assuming there is no override or Overload. When a subclass calls a method that does not have a subclass, it actually calls the parent class.


Overloading is the same method name, but the name of the parameter is different, in order to prevent you from overloading the wrong to add the @override tag, you will be prompted not to override the Method.


(5) protected

Java programming idea (iii)--control of access permission
In the previous article written in advance, because not before the inheritance of things.


Can simply regard protected as the inheritance of the father to the son, other non-inheriting classes can not access to Ask.


(6) Finalkeyword

Add the basic type of finalkeyword, which means that the variable will not change after Initialization. C-like Define. You want a variable in this program that the value does not need to be changed. will be able to use Final.

public class son{    int  = 2;    public static void main (string[] Args) {                final int i = 1;        i = 2;  The value can no longer be changed to        final son son = new son ();  son = new son ();        The final local variable son cannot be Assigned.         It must is blank and not using a compound assignment        //final decorated local variable son cannot be assigned, must be empty or not reassigned                son.age = 4;        Although the reference is Constant. however, The object itself can be Changed.    }        void change  (final int C) {        ///c= this.age; could not be given a new value because the value simply has a reference to the method   and this similar        //age + +;       Cannot be changed    }}

Static initialization, which is used in conjunction with final, occupies a storage space that cannot be changed.

Static final is the Compile-time Constant. Constant names are traditionally named according to the constants of C. The practical uppercase Letters. The words are separated by underscores.

Static Final Value_one = 1.


When the final decoration method

public class Print {    final void cannotprint () {        System.out.println (1);}    } public class Printson extends print{    //void cannotprint () {}    //cannot be overridden because the public        static void main is final decorated ( string[] Args) {        Printson ps = new Printson ();        Ps.cannotprint ();    }}

Can be seen as a parent class that requires subclasses to inherit the immutable property (ancestral). Private is implicitly specified as Final. Because private does not give you inheritance at All. It's more private than you can inherit but not Change.


By the way, clarify the Permissions.

Public property, not just subclasses, other classes can also be used.

final, ancestral treasures, reserved for subclasses, but do not agree to Change.

private, the parent class is privately owned and will not inherit from the Subclass.

Protected The parent class is reserved for the property of the subclass, which cannot be used by Others.


When the final decoration is the class. is to keep this class from being Inherited.


(7) Inheritance and initialization

The order problem here is a very interesting question.

See Examples.

Class grandfather{    private static int i = Print ();    private static int print () {        System.out.println ("g");        return 1;}    } Class Father extends grandfather{    private static int i = Print ();    private static int print () {        System.out.println ("f");        return 1;}    } public class Son extends father{    private static int i = Print ();    private static int print () {        System.out.println ("s");        return 1;    }    public static void main (string[] Args) {        System.out.println ("first");}    }

Is the result of printing first? Wrong.

Although the Main method is Running. But see son this I need static initialization not, The result is S. first?

This also has the problem of initialization, son is inheriting father. Then the compiler will load the Father. and Initialize I. That father inherits Grandfather. Then the compiler will load the grandfather, similar to Recursion.

The last one that was initialized first was the grandfather I.

So the final result is: G,f,s,first.


As for the upward transformation mentioned in this Chapter. is associated with polymorphism, so put it in the next Article.

One of the three basic characteristics of Object-oriented--java programming thought (v)-polymorphism.


Java Programming Idea (iv)--reuse class

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.