The combination mechanism of classes in Java

Source: Internet
Author: User

through the classroom learning, understand the class of the combination mechanism, before just introduced the Java class inheritance, ignoring the combination of classes, today to fill in.

In Java if you have a method in Class A that you want to invoke, when you create a new class B, you can consider the object reference of Class A as a data member, and you can think of Class B as a combination of Class A.

In a concrete example, explain:

This example is to create a class a,a has a firing method, and the known class Fighterplane has this method, so you want to use a ready-made method, the combination of classes. The object of a can call the Fighterplane method, so the class A must have a data member of the reference type of the Fighterplane object, and then initialize the data member to associate it with a Fighterplane object. That is, you need to pass in an argument to the constructor method of Class A to initialize it. Fighterplane ftp = new Fighterplane ("Su35", 10); A Fighterplane object and a reference to this object are generated, followed by a = new A (FTP); The initialization of the FP in a is completed, and the Class A object can call the Fighterplane method.

In essence, a Class A data member data type is very special, but the same as the simple data type, is also initialized. In addition, the advantages of class composition, the combination of classes using object references, can be associated with different objects, but when the class inherits, the subclass inherits all the data members and methods of the parent class, it is cumbersome. So try to use a combination, less inheritance.

The combination mechanism of classes in Java

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.