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.