The reuse Class re-uses the previously written code and does not need to be re-encoded. It has two forms:
First, use the class without damaging the existing program code. This method is intuitive, and you only need to generate the existing class object in the new class, because the new class is composed of the objects of the existing class, it is also called a combination.
Second, create a new class based on the existing class type.
Combined Learning
1. Syntax: place the object reference in the new class.
For example:
package tst;class WaterSource {private String s;WaterSource(){System.out.println("WaterSource()");s = "Constructed";}public String toString(){return s;}}public class ZhuheTest {private String value1,value2,value3,value4;private WaterSource source = new WaterSource();private int i;private float f;public String toString(){return "value1 = " + value1 + " " +"value2 = " + value2 + " " +"value3 = " + value3 + " " +"value4 = " + value4 + " " +"i = " + i + " " + "f = " + f + "\n" +"source = "+ source;}public static void main(String[] args) {ZhuheTest test = new ZhuheTest();System.out.println(test);}}
1: Where the object is defined. It can always be initialized before the constructor is called.
2: In the constructor of the class.
3: Before using these objects, this method is called inert initialization.
4: Use instance initialization.
The following are examples of the four methods:
package tst;class Soap {private String s;Soap(){System.out.println("Soap()");s = "Constructed";}public String toString(){return s;}}public class Composition {private String s1="happy",s2="Happy",s3,s4;private Soap castille;private int i;private float toy;public Composition(){System.out.println("Inside Bsath()");s3 = "joy";toy = 3.14f;castille = new Soap();}{i = 47;}public String toString() {if(s4 == null)s4 = "joy";return"s1 = " +s1 + "\n" +"s2 = " +s2 + "\n" +"s3 = " +s3 + "\n" +"s4 = " +s4 + "\n" +"i = " + i + "\n" + "toy = "+ toy +"\n" +"castille = "+ castille;}public static void main(String[] args) {Composition test = new Composition();System.out.println(test);}}
The above is a learning Summary of the combination and the initialization;
Inheritance Learning
- Inheritance is an indispensable part of all OOP and Java languages. When creating a class without specifying to inherit that class, it generally inherits from: object.
- Initialize base class: The base class constructor is called in the constructor to perform initialization. The base class constructor has all the knowledge and capabilities required to perform base class initialization.
package tst;class Art {Art(){System.out.println("Art constructor");}}class Drawing extends Art {Drawing(){System.out.println("Drawing constructor");}}public class Cartoon extends Drawing{public Cartoon(){System.out.println("Cartoon constructor");}public static void main(String[] args) {Cartoon x = new Cartoon();}}
Output result: Art Constructor
Drawing Constructor
Cartoon Constructor