Java Tour (vi)--single case design pattern, inheritance extends, aggregation relationship, child parent class variable relationship, Super, overlay

Source: Internet
Author: User
Tags stub

Java Tour (vi)--single case design pattern, inheritance extends, aggregation relationship, child parent class variable relationship, Super, overlay

Java also more and more deep, everyone refueling it! Let's take a step

I. Single-CASE design mode
    • What is design mode?

      There are 23 design patterns in Java, the most effective way to solve a problem

    • Single Case design mode

      Resolves a class that only has one object in memory

Want to make sure the object is the only thing to do

    • 1. To prevent other programs from creating such objects too much, first prevent other programs from establishing such objects
    • 2. In order for other programs to access this class object, you have to customize an object in this class
    • 3. In order to facilitate the access of other programs to the custom object, you can provide some external access methods

How do these three steps come true?

    • 1. Privatize the constructor
    • 2. Create an object of this class in a class
    • 3. Provides a way to get to the object

And then our code came out.

/** * 单例模式 *  * @author LGL * */publicclass Single {    // 将构造函数私有化    privateSingle() {    }    // 在类中创建一个本类对象    privatestaticnew Single();    // 提供一个方法可以获取到该对象    publicstaticgetInstance() {        return s;    }}

Of course, we still have a way of writing--lazy-

/** * Singleton mode * Lazy type * @author  LGL * */ public  < Span class= "Hljs-keyword" >class  single  {     Private  static  single s = null ; public  single  () {//TODO auto-generated constructor stub } p Ublic  static  single getinstance  () {if  (s = = null ) s = new         single ();    return  s; }}

There's a way to do that.

/** * 单例模式  * 饿汉式 *  * @author LGL * */publicclass Single {    privatestaticnew Single();    publicSingle() {        // TODO Auto-generated constructor stub    }    publicstaticgetInstance() {        return s;    }}

There are a variety of ways to do this, as long as you master the idea.

A Hungry man features: Single class into memory has created the object
Lazy Features: objects are initialized when the method is called, or lazy loading of objects

The single class into memory does not exist, only the getinstance () method is called to establish the object, which is called lazy loading

We generally use a hungry man type, because he is safe, simple

Two. Inheritance

An idea in object-oriented thinking, inherited, we can understand that, we can define a student class, he has a name and age, there is a way to learn

/** * 学生 * @author LGL * */class Student {    String name;    int age;    void study() {        System.out.println("学习");    }}

And then we can define a worker class.

/** * 工人 * @author LGL * */class Worker {    String name;    int age;    void work() {        System.out.println("工作");    }}

He also has a name and age and a way to work.

This time we can find that they all have the same relationship, they are people, people have age and name, so we can take the students and workers to describe the commonalities, as long as the students and workers with the individual description of the class has a relationship to the line, that is, inheritance

/** * 人 *  * @author LGL * */class Person {    String name;    int age;}

This person is called the parent class, super class, base class

And then our workers and students can write it like this.

/** * 学生 *  * @author LGL * */class Student extends Person {    void study() {        System.out.println("学习");    }}/** * 工人 *  * @author LGL * */class Worker extends Person {    void work() {        System.out.println("工作");    }}

They are the subclass of person, inheritance is from life, so workers can not inherit students, no ethics, do not want to get other class functions, simplify the code and inheritance, must be the class and the class has a relationship to inherit, is a relationship
Advantages of inheritance

    • 1. Improve the reusability of code
    • 2. Having a relationship between classes and classes has a polymorphic nature with this layer of relationships

In the Java language, Java only supports single inheritance and does not support multiple inheritance

    • Why not inherit more?

      Because multiple inheritance is a security risk, when the same functionality is defined in multiple parent classes, the subclass object is not sure which one to run when the feature content is different, but Java retains this mechanism and is represented by another form of representation, many implementations.


Java supports multiple layers of inheritance, i.e. an inheritance system

How do I use the functionality of an inheritance system?

    • Want to use the system, first consult the description of the parent class in the system, because the parent class is defined in the system of the common content, by understanding the common function can know the basic function of the system, then, so the system can be used basically.

    • So when collective invocation, to create the object of the most subclass, why? One is because it is possible that the parent class cannot create the object, and the second is to create a subclass object that may use more functionality, including basic and special

Simply put: Check the parent class feature to create a subclass object using function

Three. Aggregation relationship

This concept may be a lot of people are not very familiar with, indeed our actual development is seldom mentioned, we object and object, not only inheritance, but also the combination of relations,

    • Polymerization

      Players are one of the teams and there are players in the team and that's the aggregation relationship.

    • Combination

      The hand is a part of the body, the leg is a part of the body, this is the combination of the relationship, you say this and the aggregation is no different, you are wrong, you know, the team is less than a player is OK, people less arms and legs on the matter oh, so the combination of a little more closely

It's all right. The object is brought together, like we inherit is a relationship of a is a, and aggregation is the relationship with a, who has who

We're not going to be doing more of this relationship.

Now that we're done, we should be able to represent it in code, and here I use the variable relationship between the subclass and the parent class when inheriting the relationship to give an example

Four. Child Parent class variable relationship

Let's explore the characteristics of class members when the parent class appears

      1. Variable
    • 2. Functions
    • 3. Constructors

Let's take a step-by-step analysis

1. Variables

Let's do a bunch of code.

//public class class namePublic class Hellojjava {    //public static no return value the Main method arraypublic static void Main (string[] str) {/** * Sub-parent class appears after the characteristics of class members * /Zi z =NewZi (); System.out.println ("NUM1 ="+ Z.NUM1 +"\ n"+"num2 ="+ z.num2); }}/** * Parent class * * @author LGL * * */ class Fu {int NUM1 =4;}/** * Sub-class * * @author LGL * * */ class Zi extends Fu {int num2 =5;}

In this way, it is not easy to know the result of the output

But we're going to be so easy, we have a special situation.

//public class class namePublic class Hellojjava {    //public static no return value the Main method arraypublic static void Main (string[] str) {/** * Sub-parent class appears after the characteristics of class members * /Zi z =NewZi (); System.out.println ("NUM1 ="+ Z.num +"\ n"+"num2 ="+ Z.num); }}/** * Parent class * * @author LGL * * */ class Fu {int num =4;}/** * Sub-class * * @author LGL * * */ class Zi extends Fu {int num =5;}

What to print now when both the subclass and the parent have the same variables?

Yes, the value of the subclass is printed, why? Because the output of NUM front is actually a default with a this, if we want to print the value of the parent class, need to add super, this is a new keyword

void show(){        System.out.println(super.num);    }

The results are obvious.

Therefore, the characteristics of the variable: if the subclass of a non-private member variable with the same name, the subclass to access the member variables in this class, with this, the subclass access the same name in the parent class variable, with the use of super,this and super almost consistent, this is a reference to this class of objects, Super represents a reference to a parent class object

But we're not going to get hurt like this. In the parent class creation and in the subclass creation, let's look at the second

2. Functions

That's the way we're supposed to be.

//public class class namePublic class Hellojjava {    //public static no return value the Main method arraypublic static void Main (string[] str) {/** * Sub-parent class appears after the characteristics of class members * /Zi z =NewZi ();        Z.show1 ();    Z.show2 (); }}/** * Parent class * * @author LGL * * */ class Fu {void Show1 () {System.out.println ("Fu"); }}/** * Sub-class * * @author LGL * * */ class Zi extends Fu {void Show2 () {System.out.println ("Zi"); }}

It's a normal implementation.

Of course we have to say a special case, the child-parent method has the same name. Let's run a little bit

This is a sub-run, and this condition is called overwrite (override), the feature of this feature

    • When a subclass has a function that is exactly the same as the parent class, when the child class object is called, it runs the contents of the subclass function, as if the parent class's function is overwritten.

When a subclass inherits the parent class, inheriting the function of the parent class into the subclass, but the subclass has the function, but the content of the function is inconsistent with the parent class, it is not necessary to define the new function, but to use the overriding attribute, preserve the function definition of the parent class and rewrite the function content

    • Covered

      1. Subclass overrides the parent class, must guarantee that the child class permission is greater than or equal to the parent class permission to overwrite, otherwise the compilation fails
      2. Static can only cover static (usually no one uses)

    • Remember

      Overloading: See only the parameter list of functions with the same name
      Overriding: Character class methods are identical, including return value types

3. Constructors

One last feature.

//public class class namePublic class Hellojjava {    //public static no return value the Main method arraypublic static void Main (string[] str) {/** * Sub-parent class appears after the characteristics of class members * /Zi z =NewZi (); }}/** * Parent class * * @author LGL * * */ class Fu {Public Fu () {System.out.println ("Fu"); }}/** * Sub-class * * @author LGL * * */ class Zi extends Fu {Public Zi () {System.out.println ("Zi"); }}

Let's run it now.

You will doubt, I clearly instantiate the subclass, how the parent class is also instantiated, because the first row of the subclass constructor has a method by default

super();

When the child class object is initialized, the constructor of the parent class is also executed, because the constructor of the subclass has an implicit statement super () in the default first row; He accesses the constructor of the parent's hollow argument, and all constructors in the subclass default the first row is super ()

    • Why must subclasses access constructors in the parent class?

      Because the data subclasses in the parent class can be obtained directly, when all subclasses establish the object, it is necessary to see how the parent class initializes the data, to first access the constructors in the parent class when all subclasses initialize them, and to access the constructor specified in the parent class by manually defining the super (XX,XX ) in a way.

    • Attention

      The super statement must be defined in the first row of the subclass constructor

    • Conclusion:

      All constructors of subclasses, by default, access the constructor of the parent's hollow argument, because the first row within each constructor of a subclass has an implicit super, and when there is no constructor for null arguments in the parent class, Subclasses must manually specify the constructors to access the parent class by using the super or this statement

Of course, a subclass's constructor can also specify this to access the constructors in this class, and at least one constructor in the subclass accesses the constructor in the parent class, which is the instantiation of the subclass, looking up

The parent class also looks up, and he's looking for all the classes in Java--object

OK, we are free to this space here, the concept of more, but difficult to digest, we want a little bit of

If you are interested in adding groups: 555974449, this is probably the most harmonious it group ever.

Java Tour (vi)--single case design pattern, inheritance extends, aggregation relationship, child parent class variable relationship, Super, overlay

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.