Let's take a look. The simplest way to reuse a class: aggregation (Aggregation)
In fact, to put it bluntly, is to create a class, and then in other places referenced to use.
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 ();}}
The test class is created, and we can come out of the program anywhere new, like New in Test2, which is actually the simplest aggregation multiplexing.
However, we need to be careful when reusing, that is, the initialization of the object.
Let's change the code above:
Package Com.ray.ch05;public class Test {public void Say () {//Added a common 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 ();}}
Run 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 is simply initialized to NULL, so there will be a run-time error.
Therefore, we must pay attention to the initialization of objects because they are not assigned by default, as is the case with the underlying type. This is the compiler's optimization strategy.
So, we Test2 the above code must instantiate the object of the test class.
Package Com.ray.ch05;public class Test2 {private Test test=new test ();p rivate void Runsay () {Test.say ();} public static void Main (string[] args) {new Test2 (). Runsay ();}}
Re-run the output:
Method say
Summary: This chapter focuses on the reuse class of aggregation syntax and some of its points of attention.
This chapter is here, thank you.
-----------------------------------
Directory
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Understanding java-6.1 Aggregation from the beginning (aggregation)