Java-6.1 aggregation)

Source: Internet
Author: User

Java-6.1 aggregation)

Let's take a look at the simplest method of reusing classes: aggregation)

To put it bluntly, we create a class and reference it elsewhere.

 

 

package com.ray.ch05;public class Test {public static void main(String[] args) {}}

package com.ray.ch05;public class Test2{public static void main(String[] args) {new Test();}}

After the Test class is created, we can create a new class anywhere in the program, just like new in Test2. In this way, it is actually the simplest aggregate reuse.

 

 

 

However, we need to pay attention to the object initialization issue when reusing it.

Let's modify the above Code:

 

Package com. ray. ch05; public class Test {public void say () {// added a public method System. out. println (method say);} public static void main (String [] args ){}}

Package com. ray. ch05; public class Test2 {private Test test; // reference Testprivate void runSay () {test. say ();} public static void main (String [] args) {new Test2 (). runSay ();}}

Running output:

 

Exception in thread main java. lang. NullPointerException
At com. ray. ch05.Test2. runSay (Test2.java: 7)
At com. ray. ch05.Test2. main (Test2.java: 11)

Null pointer error, because we did not instantiate the object test in Test2, and the default compiler only initialized to null, so there will be a runtime error.

Therefore, we must pay attention to object initialization, because they are not the same as the basic type, the compiler assigns values by default. This is the compiler optimization policy.

Therefore, the code above Test2 must instantiate the object of the Test class.

 

package com.ray.ch05;public class Test2 {private Test test=new Test();private void runSay() {test.say();}public static void main(String[] args) {new Test2().runSay();}}

Run the output again:

 

Method say

 

Summary: This chapter mainly discusses the reusable classes of aggregate syntax and some points of attention.

 

 

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.